o
    +i8%                    @  s  U 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
Z
ddlmZmZmZ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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'm(Z( ddl)m*  m+Z+ ddl,m-Z. dd	l,m/Z/m0Z0m1Z1 dd
l2m3Z4 ddl5m6Z6 ddl7m8Z8 erddl9m:Z: ddl;m<Z< e	=e>Z?e+j@e+jAe+jBe+jCe+jDe+jEe/jFe/jGdZHdeId< dZJdaKdeId< dddZLdddZM	ddd!d"ZNejOddddddddd#dd4d5ZPeLZQdd8d9ZRdddddddddd:	ddGdHZSddKdLZTG dMdN dNedOdPZUedQdRdSZVe%dTZWe#G dUdV dVeeeWeVf ZXddWdd]d^ZYe"dd_d`ZZe"	addddddddddddOdbddhd`ZZddkd`ZZG dldm dmZ[ddndoZ\ddrdsZ]h dtZ^G dudv dvedOdPZ_G dwdx dxedOdPZ`		ddd}d~ZadddZb	ddddZc			ddddZd			ddddZedddZfdddZgdddZhddddZi	ddddZjejkdd	ddddZl	ddddZmdddddZnddddZo	ddddZpdddddZqedZrG dd deer ZsG dd deseer ZtG dd deseer ZudddZvdddƄZwdddȄZxdddʄZye+jAZAe+jBZBe+jCZCe+jDZDe+jEZEe+j@Z@dS )z1Decorator for creating a run tree from functions.    )annotationsN)AsyncGeneratorAsyncIterator	Awaitable	GeneratorIteratorMappingSequence)copy_context)TYPE_CHECKING	AnnotatedAnyCallableGenericLiteralOptionalProtocol	TypedDictTypeVarUnioncastget_type_hintsoverloadruntime_checkable)	ParamSpec	TypeGuardget_args
get_originclient)	run_treesschemasutils)_aiter)_runtime_env)WriteReplica)TracebackType)Runnableparentproject_nametagsmetadataenabledr   replicasdistributed_parent_idz!dict[str, contextvars.ContextVar]_CONTEXT_KEYSzlangsmith/run_helpers.pyOptional[bool]_OTEL_AVAILABLEreturnOptional[run_trees.RunTree]c                   C  s
   t j S )zGet the current run tree.)_context_PARENT_RUN_TREEget r8   r8   R/var/www/html/psymed-ai/venv/lib/python3.10/site-packages/langsmith/run_helpers.pyget_current_run_treeH   s   
r:   r,   r   Nonec                  K  s,   t  }|du rtd dS |j|  dS )z(Update metadata on the current run tree.NzFNo active run tree found. Call `set_run_metadata` inside a traced run.)r:   LOGGERwarningr,   update)r,   run_treer8   r8   r9   set_run_metadataM   s   r@   contextOptional[contextvars.Context]dict[str, Any]c              	     sd    du r't j t j t j t j t j t j tj	 tj
 dS  fddt D S )z Get the current tracing context.Nr(   c                   s   i | ]
\}}|  |qS r8   r7   .0kvrA   r8   r9   
<dictcomp>h   s    z'get_tracing_context.<locals>.<dictcomp>)r5   r6   r7   _PROJECT_NAME_TAGS	_METADATA_TRACING_ENABLED_CLIENTr    	_REPLICAS_DISTRIBUTED_PARENT_IDr0   itemsrI   r8   rI   r9   get_tracing_contextY   s   
rS   )r*   r+   r,   r)   r-   r   r.   r/   r*   Optional[str]r+   Optional[list[str]]Optional[dict[str, Any]]r)   @Optional[Union[run_trees.RunTree, Mapping, str, Literal[False]]]r-   'Optional[Union[bool, Literal['local']]]r   Optional[ls_client.Client]r.    Optional[Sequence[WriteReplica]]r/   kwargsGenerator[None, None, None]c              
   k  s    |rt d| dt t }	|durtd|p|dind}
|}|du rF|
durFtt|p0g t|
jp6g B }i |
j	|pAi }|
j
}|durL|n|	d}t|
| ||||||d z
dV  W t|	 dS t|	 w )	a  Set the tracing context for a block of code.

    Args:
        project_name: The name of the project to log the run to.
        tags: The tags to add to the run.
        metadata: The metadata to add to the run.
        parent: The parent run to use for the context.

            Can be a Run/`RunTree` object, request headers (for distributed tracing),
            or the dotted order string.
        client: The client to use for logging the run to LangSmith.
        enabled: Whether tracing is enabled.

            Defaults to `None`, meaning it will use the current context value or environment variables.
        replicas: A sequence of `WriteReplica` dictionaries to send runs to.

            Example: `[{"api_url": "https://api.example.com", "api_key": "key", "project_name": "proj"}]`
            or `[{"project_name": "my_experiment", "updates": {"reference_example_id": None}}]`
        distributed_parent_id: The distributed parent ID for distributed tracing. Defaults to None.
    z Unrecognized keyword arguments: .Fr)   
parent_runNr-   r(   )warningswarnDeprecationWarningrS   _get_parent_runr7   sortedsetr+   r,   id_set_tracing_context)r*   r+   r,   r)   r-   r   r.   r/   r[   current_contextr^   distributed_parent_id_to_user8   r8   r9   tracing_contextk   s>   !
ri   func'TypeGuard[SupportsLangsmithExtra[P, 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__)_is_traceable_function
isinstance	functoolspartialrj   hasattrrl   rj   r8   r8   r9   is_traceable_function   s
   rs   	namer,   r+   r   	reduce_fnr*   process_inputsprocess_outputsprocess_chunkCallable[P, R]ru   Optional[Mapping[str, Any]]rv   0Optional[Callable[[Sequence], Union[dict, str]]]rw    Optional[Callable[[dict], dict]]rx   Optional[Callable[..., dict]]ry   Optional[Callable]SupportsLangsmithExtra[P, R]c       	   
      C  s*   t | r| S t|||||||||	d	| S )z$Ensure that a function is traceable.rt   )rs   	traceable)
rj   ru   r,   r+   r   rv   r*   rw   rx   ry   r8   r8   r9   ensure_traceable   s   
r   r   boolc                 C  s    t | pt| dot | jS )z;Inspect function or wrapped function to see if it is async.__wrapped__)inspectiscoroutinefunctionrq   r   rr   r8   r8   r9   is_async   s   
r   c                   @  s   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ed< 	 ded< 	 ded< ded< dS )LangSmithExtraz<Any additional info to be injected into the run dynamically.rT   ru   Optional[ls_client.ID_TYPE]reference_example_idOptional[dict]	run_extraz0Optional[Union[run_trees.RunTree, str, Mapping]]r)   r4   r?   r*   rV   r,   rU   r+   run_idrY   r   z-Optional[Callable[[run_trees.RunTree], None]]_on_success,Optional[Callable[[run_trees.RunTree], Any]]on_endN__name__
__module____qualname____doc____annotations__r8   r8   r8   r9   r      s2   
 r   F)totalRT)	covariantPc                   @  s    e Zd ZdZdddddZdS )SupportsLangsmithExtrazNImplementations of this Protocol accept an optional langsmith_extra parameter.Nlangsmith_extraargsP.argsr   Optional[LangSmithExtra]r[   P.kwargsr3   r   c                O  s   dS )aj  Call the instance when it is called as a function.

        Args:
            *args: Variable length argument list.
            langsmith_extra: Optional dictionary containing additional
                parameters specific to Langsmith.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            R: The return value of the method.

        Nr8   )selfr   r   r[   r8   r8   r9   rl     s   zSupportsLangsmithExtra.__call__)r   r   r   r   r[   r   r3   r   )r   r   r   r   rl   r8   r8   r8   r9   r     s    r   outputsr?   run_trees.RunTreer   r   (Optional[schemas.ExtractedUsageMetadata]c                 K  s"   | j pi d}|pi dp|S )Nusage_metadata)r,   r7   )r?   r   r[   from_metadatar8   r8   r9   _extract_usage  s   r   c                 C     d S Nr8   rr   r8   r8   r9   r   &  s   r   chain)ru   r,   r+   r   rv   r*   rw   rx   ry   _invocation_params_fndangerously_allow_filesystemrun_typels_client.RUN_TYPE_Tr   r   8Callable[[Callable[P, R]], SupportsLangsmithExtra[P, R]]c                C  r   r   r8   )r   ru   r,   r+   r   rv   r*   rw   rx   ry   r   r   r8   r8   r9   r   ,  s   r   /Union[Callable, Callable[[Callable], Callable]]c                    sv  t tj| rt| d tr| d n|ddpdtvr,td dt d d t	| d	kr7td
 d|v rAtdt
 |ddt|dd|dd|dd|dd|dd|dd|dd|dd|dd|ddd|dd}tjt|d |rtdt|  dt
 d! fdd }t	| d	krt| d r|s|| d S |S )"a  Trace a function with langsmith.

    Args:
        run_type: The type of run (span) to create.

            Examples: `llm`, `chain`, `tool`, `prompt`, `retriever`, etc.

            Defaults to "chain".
        name: The name of the run. Defaults to the function name.
        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.
        project_name: The name of the project to log the run to.

            Defaults to `None`, which will use the default project.
        process_inputs: Custom serialization / processing function for inputs.

            Defaults to `None`.
        process_outputs: Custom serialization / processing function for outputs.

            Defaults to `None`.
        dangerously_allow_filesystem: Whether to allow filesystem access for attachments.

            Defaults to `False`.

            Traces that reference local filepaths will be uploaded to LangSmith.
            In general, network-hosted applications should not be using this because
            referenced files are usually on the user's machine, not the host machine.

    Returns:
        The decorated function.

    !!! note

        Requires that `LANGSMITH_TRACING_V2` be set to 'true' in the environment.

    Examples:
        !!! example "Basic usage"

            ```python
            @traceable
            def my_function(x: float, y: float) -> float:
                return x + y


            my_function(5, 6)


            @traceable
            async def my_async_function(query_params: dict) -> dict:
                async with httpx.AsyncClient() as http_client:
                    response = await http_client.get(
                        "https://api.example.com/data",
                        params=query_params,
                    )
                    return response.json()


            asyncio.run(my_async_function({"param": "value"}))
            ```

        !!! example "Streaming data with a generator"

            ```python
            @traceable
            def my_generator(n: int) -> Iterable:
                for i in range(n):
                    yield i


            for item in my_generator(5):
                print(item)
            ```

        !!! example "Async streaming data"

            ```python
            @traceable
            async def my_async_generator(query_params: dict) -> Iterable:
                async with httpx.AsyncClient() as http_client:
                    response = await http_client.get(
                        "https://api.example.com/data",
                        params=query_params,
                    )
                    for item in response.json():
                        yield item


            async def async_code():
                async for item in my_async_generator({"param": "value"}):
                    print(item)


            asyncio.run(async_code())
            ```

        !!! example "Specifying a run type and name"

            ```python
            @traceable(name="CustomName", run_type="tool")
            def another_function(a: float, b: float) -> float:
                return a * b


            another_function(5, 6)
            ```

        !!! example "Logging with custom metadata and tags"

            ```python
            @traceable(
                metadata={"version": "1.0", "author": "John Doe"}, tags=["beta", "test"]
            )
            def tagged_function(x):
                return x**2


            tagged_function(5)
            ```

        !!! example "Specifying a custom client and project name"

            ```python
            custom_client = Client(api_key="your_api_key")


            @traceable(client=custom_client, project_name="My Special Project")
            def project_specific_function(data):
                return data


            project_specific_function({"data": "to process"})
            ```

        !!! example "Manually passing `langsmith_extra`"

            ```python
            @traceable
            def manual_extra_function(x):
                return x**2


            manual_extra_function(5, langsmith_extra={"metadata": {"version": "1.0"}})
            ```
    r   r   Nr   zUnrecognized run_type: z. Must be one of: z . Did you mean @traceable(name='z')?   zThe `traceable()` decorator only accepts one positional argument, which should be the run_type. All other arguments should be passed as keyword arguments.extrazJThe `extra` keyword argument is deprecated. Please use `metadata` instead.rv   ru   r,   r+   r   r*   rw   ry   r   r   F)extra_outerru   r,   r+   r   r*   r   rw   ry   invocation_params_fnr   rx   )outputs_processorzHThe following keyword arguments are not recognized and will be ignored: r]   rj   r   c           
   	     s  t  }|jdd d u|jdd d u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 d dd fdd}t d dd fdd}t  r|}nt  r|}nt rr|}n
|}nr|}n|}t	|dd t |}	|	jds|	j
g dd |	j D t jdt jjd ddd |	j D d}	|	|_|S ) Nr?   configr   r   r   r   r   r[   r3   c           	   
     s  s	 dd tjt|  dI dH }zt }r$|d d< t|d rg fdd}|rEtj| |d d	I dH }nXtdi t	|d  | I dH }W d   n1 saw   Y  n6 i }|r}tj||d d	I dH }n tdi t	|d  |I dH }W d   n1 sw   Y  W n t
y } zt| ttj||d
I dH   d}~ww tj||dI dH  |S )z"Async version of wrapper function.r   Ncontainer_inputr   r   r[   new_runr?   c                     s>     i I d H W  d    S 1 sw   Y  d S r   r8   r8   r   rj   r[   otel_context_managerr8   r9   run_with_otel_context4  s   $zRtraceable.<locals>.decorator.<locals>.async_wrapper.<locals>.run_with_otel_contextrA   rI   errorr   r8   )pop
aitertoolsaio_to_thread
_setup_runasyncio_accepts_context_maybe_create_otel_contextasynciocreate_taskri   rS   BaseException_cleanup_tracebackshield)	r   r   r[   run_containeraccepts_contextr   function_resultfr_coroe)_on_run_endr   rj   func_accepts_configfunc_accepts_parent_runr   r[   r   r9   async_wrapper  sj   	



z3traceable.<locals>.decorator.<locals>.async_wrapperr   c           
       s  s	| dd  tjt| ||dI d H }g }zsr"|d |d< t|d }|i |}t }t|rg|rGtj	||d dI d H }n t
di t|d  |I d H }W d    n1 sbw   Y  t|||d ru|d jdknd||d	|d
2 z	3 d H W }|V  q6 W n# ty }	 zt|	 ttj ||	t|dI d H   d }	~	ww tj |t|dI d H  d S )Nr   r   r   r?   rA   rI   llmFry   )	generatorr   
is_llm_runr   resultsry   r   r   r   r   r8   )r   r   r   r   r   r   r   iscoroutiner   r   ri   rS   _process_async_iteratorr   r7   r   r   r   _get_function_result)
r   r   r[   r   r   r   async_gen_resultr   itemr   r   r   rj   r   r   rv   r8   r9   async_generator_wrapperZ  sz   


z=traceable.<locals>.decorator.<locals>.async_generator_wrapperc              
     s   s dd t|  d}tjdddu}z1|r&|d d< t|d r? fdd}|d |}n|d jg R i }W n tye } zt	| ||d	  d}~ww ||d
 |S )>Create a new run or create_child() if run is passed in kwargs.r   Nr   r?   r   c                     s6     i W  d    S 1 sw   Y  d S r   r8   r8   r   r8   r9   r     s   $zLtraceable.<locals>.decorator.<locals>.wrapper.<locals>.run_with_otel_contextrA   r   r   )
r   r   r   	signature
parametersr7   r   runr   r   )r   r   r[   r   r   r   r   r   )r   r   rj   r   r   r9   wrapper  sL   z-traceable.<locals>.decorator.<locals>.wrapperc           
   
   ?  s   s	| dd  t| ||d}tjdd d u}g }d }z9|r+|d |d< |d jg|R i |}t|d }t||dk|d|dE d H }|d urZ|	| W n t
yv }	 zt|	  ||	t|d	  d }	~	ww  |t|d
 |S )Nr   r   r?   r   rA   r   ry   )r   r   ry   r   r   r   )r   r   r   r   r   r7   r   r   _process_iteratorappendr   r   r   )
r   r   r[   r   r   r   function_returngenerator_resultr   r   )r   r   rj   r   rv   r   r8   r9   generator_wrapper  sX   	
z7traceable.<locals>.decorator.<locals>.generator_wrapperc              
     s   s| dd  t| ||d}zr|d |d< |d jg|R i |}W n ty@ } zt|  ||d  d }~ww t|drLt||S t|drWt||S  ||d	 |S )
Nr   r   r   r?   rA   r   __iter__	__aiter__r   )r   r   r   	Exceptionr   rq   _TracedStream_TracedAsyncStreamr   r   r[   trace_containerstreamr   r   r8   r9   stream_wrapper  s2    

z4traceable.<locals>.decorator.<locals>.stream_wrapperc              
     s   s	| dd  tjt| ||dI d H }zr |d |d< |i |I d H }W n tyC } ztj ||dI d H   d }~ww t|drOt||S t|drZt||S tj ||dI d H  |S )	Nr   r   r   r?   r   r   r   r   )r   r   r   r   r   rq   r   r   r   r   r8   r9   async_stream_wrapper)  s4   	

z:traceable.<locals>.decorator.<locals>.async_stream_wrapper__langsmith_traceable__Tc                 s  s"    | ]}|j tjjkr|V  qd S r   kindr   	ParameterVAR_KEYWORDrF   paramr8   r8   r9   	<genexpr>]      z/traceable.<locals>.decorator.<locals>.<genexpr>)defaultc                 s  s"    | ]}|j tjjkr|V  qd S r   r   r   r8   r8   r9   r   e  r   )r   )r   r   r   r   r[   r   r3   r   )r   r   r   r   r[   r   r3   r   )r   r   r   r7   ro   wrapsisasyncgenfunctionisgeneratorfunctionr   setattrreplacevaluesr   KEYWORD_ONLY__signature__)
rj   func_sigr   r   r   r   r   r   selected_wrappersigr   r   rv   r   )rj   r   r   r9   	decorator  sh   
AG-7 
 


	ztraceable.<locals>.decorator)rj   r   )r   	ls_client
RUN_TYPE_Trn   strr   _VALID_RUN_TYPESr_   r`   lenra   _ContainerInputro   rp   _handle_container_endrc   keyscallable)r   r[   r   r  r8   r  r9   r   >  sp    !











  `c                   @  s   e Zd ZdZ	d6ddddddddddddd7dd Zd8d#d$Zd9d,d-Zd8d.d/Z			d:d9d0d1Zd8d2d3Z				d:d9d4d5Z
dS );tracea  Manage a LangSmith run in context.

    This class can be used as both a synchronous and asynchronous context manager.

    Args:
        name: Name of the run.
        run_type: Type of run (e.g., `'chain'`, `'llm'`, `'tool'`).
        inputs: Initial input data for the run.
        project_name: Project name to associate the run with.
        parent: Parent run.

            Can be a `RunTree`, dotted order string, or tracing headers.
        tags: List of tags for the run.
        metadata: Additional metadata for the run.
        client: LangSmith client for custom settings.
        run_id: Preset identifier for the run.
        reference_example_id: Associates run with a dataset example.

            Only for root runs in evaluation.
        exceptions_to_handle: Exception types to ignore.
        extra: Extra data to send to LangSmith.

            Use 'metadata' instead.

    Examples:
        Synchronous usage:

        ```python
        with trace("My Operation", run_type="tool", tags=["important"]) as run:
            result = "foo"  # Perform operation
            run.metadata["some-key"] = "some-value"
            run.end(outputs={"result": result})
        ```

        Asynchronous usage:

        ```python
        async def main():
            async with trace("Async Operation", run_type="tool", tags=["async"]) as run:
                result = "foo"  # Await async operation
                run.metadata["some-key"] = "some-value"
                # "end" just adds the outputs and sets error to None
                # The actual patching of the run happens when the context exits
                run.end(outputs={"result": result})


        asyncio.run(main())
        ```

        Handling specific exceptions:

        ```python
        import pytest
        import sys

        with trace("Test", exceptions_to_handle=(pytest.skip.Exception,)):
            if sys.platform == "win32":  # Just an example
                pytest.skip("Skipping test for windows")
            result = "foo"  # Perform test operation
        ```
    r   N)inputsr   r*   r)   r+   r,   r   r   r   exceptions_to_handleattachmentsru   r  r   r   r  r   r   r*   rT   r)   COptional[Union[run_trees.RunTree, str, Mapping, Literal['ignore']]]r+   rU   r,   r{   r   rY   r   r   r   r  )Optional[tuple[type[BaseException], ...]]r  Optional[schemas.Attachments]r[   r   c                K  s   | dd| _|rtdt|  dt || _|| _|| _	|| _
|| _|| _|| _|d| _|| _|| _|	| _|
| _|| _|| _d| _d| _dS )z_Initialize the trace context manager.

        Warns if unsupported kwargs are passed.
        _end_on_exitTzEThe `trace` context manager no longer supports the following kwargs: r]   r?   N)r   r  r_   r`   rc   r  ra   ru   r   r  r  r   r*   r)   r7   r?   r+   r,   r   r   r   r  r   old_ctx)r   ru   r   r  r   r*   r)   r+   r,   r   r   r   r  r  r[   r8   r8   r9   __init__  s0   

ztrace.__init__r3   r   c           
      C  s  t  | _t| j}tj ptj}tj ptj	}| j
p"| jd}t| j| j|| jd}tt| jp5g |p8g  }i | jpAi |pEi ddi}| jpOi }||d< t| j}	|durr|rr|j| j| j| j|| j|| jd| _n(tj| jt| jtj| j dd	| j||	pd
tj! | jpi ||| jpi d| _|du r| j"  |rtj| tj| tj#| j tj$|	 tj%| | jS )a]  Set up the tracing context and create a new run.

        This method initializes the tracing context, merges tags and metadata,
        creates a new run (either as a child of an existing run or as a new root run),
        and sets up the necessary context variables.

        Returns:
            run_trees.RunTree: The newly created run.
        r   )r)   r?   r   r*   	ls_methodr  r,   N)ru   r   r   r   r  r+   r  Taccept_nullr   )ru   re   r   r   r   r*   r.   r  r+   r   r  )&rS   r  r"   tracing_is_enabledr5   rL   r7   _GLOBAL_TAGSrM   _GLOBAL_METADATAr   rb   r)   r?   r*   rc   rd   r+   r,   r   _get_project_namecreate_childru   r   r   r  r  r   r    RunTreer  _ensure_uuidr   rP   postr6   rK   rO   )
r   r-   
outer_tagsouter_metadataclient_parent_run_tags_r,   r   project_name_r8   r8   r9   _setup  sr   
	





ztrace._setupexc_typeOptional[type[BaseException]]	exc_valueOptional[BaseException]	tracebackOptional[TracebackType]r;   c                 C  s   | j du rdS |dur-| jrt|| jrd}nt }|j d| d| }| j j|d | jdurKt| j}|du rD| j	rD| j 
  t| j dS tdt dS )a  Clean up the tracing context and finalize the run.

        This method handles exceptions, ends the run if necessary,
        patches the run if it's not disabled, and resets the tracing context.

        Args:
            exc_type: The type of the exception that occurred, if any.
            exc_value: The exception instance that occurred, if any.
            traceback: The traceback object associated with the exception, if any.
        N: 

r   Tz(Tracing context was not set up properly.)r   r  
issubclassr"   _format_excr   endr  r#  r  patchrf   r_   r`   RuntimeWarning)r   r2  r4  r6  tbr-   r8   r8   r9   	_teardown3  s    


ztrace._teardownc                 C  s   |   S )zyEnter the context manager synchronously.

        Returns:
            run_trees.RunTree: The newly created run.
        )r1  r   r8   r8   r9   	__enter__W  s   ztrace.__enter__c                 C  s   |  ||| dS )a  Exit the context manager synchronously.

        Args:
            exc_type: The type of the exception that occurred, if any.
            exc_value: The exception instance that occurred, if any.
            traceback: The traceback object associated with the exception, if any.
        N)r@  )r   r2  r4  r6  r8   r8   r9   __exit___  s   ztrace.__exit__c                   s.   t  }tj| j|dI dH }tt| |S )zzEnter the context manager asynchronously.

        Returns:
            run_trees.RunTree: The newly created run.
        __ctxN)r
   r   r   r1  rf   rS   )r   ctxresultr8   r8   r9   
__aenter__n  s
   ztrace.__aenter__c              	     s`   t  }|durttj| j||||dI dH  ntj| j||||dI dH  tt| dS )a  Exit the context manager asynchronously.

        Args:
            exc_type: The type of the exception that occurred, if any.
            exc_value: The exception instance that occurred, if any.
            traceback: The traceback object associated with the exception, if any.
        NrD  )r
   r   r   r   r   r@  rf   rS   )r   r2  r4  r6  rF  r8   r8   r9   	__aexit__z  s   ztrace.__aexit__r   )ru   r  r   r   r  r   r   r   r*   rT   r)   r  r+   rU   r,   r{   r   rY   r   r   r   r   r  r  r  r  r[   r   )r3   r   )r2  r3  r4  r5  r6  r7  r3   r;   NNN)r   r   r   r   r  r1  r@  rB  rC  rH  rI  r8   r8   r8   r9   r  w  s8    A
2
K
$

r  c                 C  s6   | r| S t  }tj p|r|jnd ptjpt S r   )r6   r7   r5   rK   session_name_GLOBAL_PROJECT_NAMEr"   get_tracer_project)r*   prtr8   r8   r9   r&    s   
r&  traceable_fnr'   c              
     s   zddl mm} ddlm m W n ty# } ztd|d}~ww t| sEzt	| }W n t
y:   d}Y nw td|  d| G  fd	d
d
|}|| S )a  Convert a function wrapped by the LangSmith `@traceable` decorator to a `Runnable`.

    Args:
        traceable_fn: The function wrapped by the `@traceable` decorator.

    Returns:
        Runnable: A `Runnable` object that maintains a consistent LangSmith
            tracing context.

    Raises:
        ImportError: If `langchain` module is not installed.
        ValueError: If the provided function is not wrapped by the `@traceable` decorator.

    Example:
        >>> @traceable
        ... def my_function(input_data):
        ...     # Function implementation
        ...     pass
        >>> runnable = as_runnable(my_function)
    r   )RunnableConfigRunnableLambda)InputOutputzjas_runnable requires langchain-core to be installed. You can install it with `pip install langchain-core`.Nz<source unavailable>zRas_runnable expects a function wrapped by the LangSmith @traceable decorator. Got z defined as:
c                      sV   e Zd ZdZ	dd fd	d
ZedfddZedfddZ  ZS )z&as_runnable.<locals>.RunnableTraceablezConverts a `@traceable` decorated function to a `Runnable`.

        This helps maintain a consistent LangSmith tracing context.
        Nrj   r   afunc*Optional[Callable[..., Awaitable[Output]]]r3   r;   c              	     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_asyncr   	TypeErrorr   r   rs   
_wrap_sync
ValueError	__class__r   superr  r   r   )r   rj   rU  wrappedawrapped)rS  rT  r[  r8   r9   r    s.   

z/as_runnable.<locals>.RunnableTraceable.__init__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  dictr   rQ  r3   r   c                   s,   t jtt|} di | dd|iiS Nr   r?   r8   r    r(  from_runnable_configr   ra  r  r   r?   rr   r8   r9   wrap_traceable  s   zIas_runnable.<locals>.RunnableTraceable._wrap_sync.<locals>.wrap_traceableNr  ra  r   rQ  r3   r   )r   r   )rj   rf  rS  rT  rQ  rr   r9   rY    s   z1as_runnable.<locals>.RunnableTraceable._wrap_sync>Optional[Callable[[Input, RunnableConfig], Awaitable[Output]]]c                   s`   | 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  ra  r   rQ  r3   r   c                   s4   t jtt|} di | dd|iiI d H S rb  rc  re  afunc_r8   r9   awrap_traceable  s    zKas_runnable.<locals>.RunnableTraceable._wrap_async.<locals>.awrap_traceablerg  )rs   rZ  r   r   r   )rU  rl  rh  rj  r9   rW    s   z2as_runnable.<locals>.RunnableTraceable._wrap_asyncr   )rj   r   rU  rV  r3   r;   )rj   r_  r3   r`  )rU  rV  r3   ri  )	r   r   r   r   r  staticmethodrY  rW  __classcell__r8   rh  r[  r9   RunnableTraceable  s     rp  )langchain_core.runnablesrQ  rR  langchain_core.runnables.utilsrS  rT  ImportErrorrs   r   	getsourcer   rZ  )rP  rR  r   fn_srcrp  r8   rh  r9   as_runnable  s4   Irv  >   r   toolr   parserprompt	embedding	retrieverc                   @  sZ   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ed< dS )_TraceableContainer3Typed response when initializing a run a traceable.r4   r   rT   r*   outer_projectrV   r,  rU   r+  r   r   r   zcontextvars.ContextrA   r1   _token_event_loggedNr   r8   r8   r8   r9   r|  #  s   
 r|  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ed< ded< ded< ded< dS )r  r}  r   r   rT   ru   rV   r,   rU   r+   rY   r   r   rv   r*   r   r   r}   rw   ry   r   r1   r   Nr   r8   r8   r8   r9   r  1  s   
 r  	containerOptional[Any]r   r5  c              
   C  s  |  d}|du rdS t|tr|}nD|durSt|drSt|jrSt|tsSz	|jddd}W n' tyR } zt	dt| d|  d	|i}W Y d}~n	d}~ww d	|i}t
||d
 }durf||jd< |rvt }t| d| }n.d}|  d }	rt|	rz|	| W n ty } ztd|  W Y d}~nd}~ww |j||d t du r|  |  d }
rt|
rz|
| W dS  ty } ztd|  W Y d}~dS d}~ww dS dS )zEnd the run.r   N
model_dumpTjson)exclude_nonemodez&Failed to use model_dump to serialize z
 to JSON: output)r?   r   r   r9  r   z$Failed to run _on_success function: r   r   r   zFailed to run on_end function: )r7   rn   ra  rq   r  r  typer   r<   debugr   r,   r"   r;  reprr   r_   r`   r<  r#  r=  )r  r   r   r?   dict_outputsr   usage
stacktrace
error_reprr   r   r8   r8   r9   _container_endB  s\   


r  r   ra  r   c                 C  s(   | dd }|ri | |}|S | }|S )Nr   rD   )r   r   r   extra_innerr8   r8   r9   _collect_extrat  s   r  r   c                 C  s   |  d}|dkrd S t|tjr|S t|tr)tjj||  dt|  ddS t|trAtjj||  dt|  dd}|S |  d}|rJ|S t	 }t
 d urstjj||  dd }rs|rq|d urk| dsq|j|jkrs|S |S )	Nr)   ignorer   r*   )r   r*   r?   r   	callbacks)r7   rn   r    r(  r   from_headersr&  r  from_dotted_orderr:   r$   get_langchain_core_versionrd  dotted_order)r   r   r)   dortr?   crtrtr8   r8   r9   rb   }  s@   





rb   r   r   c           $      C  s  | dpi }| d}| d}| d}| dpd}	| dd}
tj  }|p,t }| d	p6| d	}| d|pAtj  }ti |d|i| d
}tj  }|pm|r\|jndpm| dpm|d pmtjpmt	 }| d}| d}|st
 sttjd td||dd| d| dt dd	S t| }|pt| }t||}tj  ptj}tj  ptj}t }i | dpi |pi }|tjj| ||pi  d|d< ||d< t|g|R d| i|\}}| d}|r2zdd || D }|rt|tr|| W n ty1 } zt !d| d|  W Y d}~nd}~ww | d}|r_z||}W n ty^ } zt !d| d|  W Y d}~nd}~ww | dpfg |pjg  } |tjj|  | |pyg 7 } |dur|j"||	|| |||d}!n-|||	t#j$|dd|t%j&  || |||
d }"|durt#$||"d!< t%j'd%i t(t)|"}!t
 du rz|!*  W n ty } zt !d"|!j+ d|  W Y d}~nd}~ww t|!||||| d| d|dd#	}#|tjj|#d  |t,j|#d$  |#S )&r   r   r,   r+   r   r   r   r   Fru   r   Nr*   r   r   z>LangSmith tracing is not enabled, returning original function.r   r   )	r   r*   r~  r,  r+  r   r   rA   r  r   r   rj   r   c                 S  s   i | ]\}}|d ur||qS r   r8   rE   r8   r8   r9   rJ     s    z_setup_run.<locals>.<dictcomp>z&Failed to infer invocation params for r8  rw   zFailed to filter inputs for )ru   r   r  r+   r   r   r  Tr!  )ru   r  r   r   r*   r.   r   r+   r   r  r   re   zFailed to post run )	r   r*   r~  r,  r+  r   r   rA   r  r   r8   )-r7   r5   rK   r   rO   rb   rL  rM  r"   rN  r#  log_onceloggingDEBUGr|  r
   r   r   _get_function_namer  rM   r%  rL   r$  r   rd   r>    _get_inputs_and_attachments_saferR   rn   ra  r   r<   r   r'  r  r)  r    rP   r(  r   r   r*  re   r6   )$rj   r   r   r   r[   r   r,   r+   r   r   r   r~  ru   r-  r.  
project_cvselected_projectr   id_r   name_r  r,  r+  rA   	metadata_r  r  r   invocation_paramsr   rw   r/  r   run_tree_kwargsresponse_containerr8   r8   r9   r     s  














"
"

$r   r   c              
   C  s`   z|dur	||}t | ||d W dS  ty/ } ztdt|  W Y d}~dS d}~ww )zHandle the end of run.Nr  z!Unable to process trace outputs: )r  r   r<   r=   r  )r  r   r   r   r   r8   r8   r9   r  =  s   "r  c                 C  s   t | ddS )Nr   F)getattrrr   r8   r8   r9   rm   L     rm   r   inspect.Signaturec                 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.r   Ncls)bind_partialapply_defaultsra  	argumentsr   r   rR   r   r   r   r   r>   )r   r   r[   boundr  
param_namer   r8   r8   r9   _get_inputsP  s   

r  c              
   O  s^   zt | g|R i |W S  ty. } ztd|  d|  ||dW  Y d }~S d }~ww NzFailed to get inputs for r8  )r   r[   )r  r   r<   r  )r   r   r[   r   r8   r8   r9   _get_inputs_safed  s   r  r   inspect.Parameterc              
   C  s   | j tjkst| j tkrtdd t| j D rdS |d ur]t| j tr]z*t	|dd}|
| j}|d urM|tjkpKt|tkoKtdd t|D W S W dS  tttfy\   Y dS w dS )Nc                 s      | ]}|t jkV  qd S r   r!   
AttachmentrF   argr8   r8   r9   r   q  s    z!_is_attachment.<locals>.<genexpr>T)include_extrasc                 s  r  r   r  r  r8   r8   r9   r   ~  s
    
F)
annotationr!   r  r   r   anyr   rn   r  r   r7   ru   	NameErrorrX  AttributeError)r   rj   
type_hintsresolved_annotationr8   r8   r9   _is_attachmentn  s.   
r  set[str]c                   s    fdd| j  D S )Nc                   s   h | ]\}}t | r|qS r8   )r  )rF   ru   r   rr   r8   r9   	<setcomp>  s    z*_attachment_args_helper.<locals>.<setcomp>)r   rR   r   rj   r8   rr   r9   _attachment_args_helper  s   
r  i  )maxsizec                 C  s
   t | |S r   )r  r  r8   r8   r9   _cached_attachment_args  s   
r  c                 C  s*   zt | |W S  ty   t| | Y S w r   )r  rX  r  r  r8   r8   r9   _attachment_args  s
   r  rr    tuple[dict, schemas.Attachments]c             
   O  s   z7t | g|R i |}t| |}|r3i i }}| D ]\}}	||v r)|	||< q|	||< q||fW S |i fW S  ty[ }
 ztd|  d|
  ||di fW  Y d }
~
S d }
~
ww r  )r  r  rR   r   r<   r=   )r   rj   r   r[   inferredattachment_argsr  r  rG   rH   r   r8   r8   r9   r    s    





r  c                 C  sP   | du rt  D ]	\}}|d qdS |  D ]\}}t | }|| qdS )zSet the tracing context.N)r0   rR   rd   )rA   rG   rH   varr8   r8   r9   rf     s   rf   r   Iterator[T]r   r   r   	list[Any]r   Generator[T, None, Any]c           
   
   #  s    zP	 |r fdd}d  |}nd  t }|r#||}n|}|rId rIdsId dtjtjj d|id	 dd< |	| |V  q t
yf }	 z	|	jW  Y d }	~	S d }	~	ww )
NTc                    sN    d} | r#t| }|r#| t W  d    S 1 sw   Y  t S Nr   )r7   r   nextr?   fresh_otel_contextr   r   r8   r9   next_with_otel_context  s   
 z1_process_iterator.<locals>.next_with_otel_contextrA   r   r  	new_tokentokenru   timer[   )r   r  r7   	add_eventdatetimenowtimezoneutc	isoformatr   StopIterationvalue)
r   r   r   r   ry   r   r  r   traced_itemr   r8   r  r9   r     sB   	

	
%r   )r   AsyncIterator[T]r   AsyncGenerator[T, None]c          
       sf  z	 |r> fdd}|rt j| d dI d H }nWtdi td  | I d H }W d    n1 s8w   Y  n5|rPt jt d dI d H }n#tdi td  t I d H }W d    n1 snw   Y  |rz||}	n|}	|rd rdsd dtj	tj
j d	|	id
 dd< ||	 |V  q ty   Y d S w )NTc                    s`    d} | r(t| }|r(| t I d H W  d    S 1 s#w   Y  t I d H S r  )r7   r   r   py_anextr  r  r8   r9   anext_with_otel_context  s   
 z8_process_async_iterator.<locals>.anext_with_otel_contextrA   rI   r   r  r  r  r  r8   )r   r   ri   rS   r   r  r7   r  r  r  r  r  r  r   StopAsyncIteration)
r   r   r   r   r   ry   r   r  r   r  r8   r  r9   r     sf   




	
9r   Tc                   @  sT   e Zd ZdZ	ddd	d
ZdddZdd Zdd Zdd Zdd Z	ddddZ
dS )_TracedStreamBasez%Base class for traced stream objects.Nr   $Union[Iterator[T], AsyncIterator[T]]r   r|  rv   r   c                 C  sD   || _ || _d| _|| _g | _|d r|d jdk| _d S d| _d S )NFr   r   )__ls_stream____ls_trace_container____ls_completed____ls_reduce_fn____ls_accumulated_output__r   __is_llm_run__)r   r   r   rv   r8   r8   r9   r  G  s   z_TracedStreamBase.__init__ru   r  c                 C  s   t | j|S r   )r  r  )r   ru   r8   r8   r9   __getattr__X  r  z_TracedStreamBase.__getattr__c                 C  s   t tt| jt| j S r   )listrd   dirr[  r  rA  r8   r8   r9   __dir__[  s   z_TracedStreamBase.__dir__c                 C  s   d| j dS )Nz
Traceable())r  rA  r8   r8   r9   __repr__^  s   z_TracedStreamBase.__repr__c                 C  s
   t | jS r   )r  r  rA  r8   r8   r9   __str__a  s   
z_TracedStreamBase.__str__c                 C  sL   z	| j s|   W n	 ty   Y nw z| j  W d S  ty%   Y d S w r   )r  
_end_tracer   r  __del__rA  r8   r8   r9   r  d  s   z_TracedStreamBase.__del__r   r5  c                 C  sJ   | j rd S z| jr| | j}n| j}t| j||d W d| _ d S d| _ w )Nr  T)r  r  r  r  r  )r   r   reduced_outputr8   r8   r9   r  o  s   z_TracedStreamBase._end_tracer   )r   r  r   r|  rv   r   )ru   r  r   r5  )r   r   r   r   r  r  r  r  r  r  r  r8   r8   r8   r9   r  D  s    
r  c                      sL   e Zd ZdZ		dd fd
dZdddZdddZdd Zdd Z  Z	S )r   z>A wrapper for synchronous stream objects that handles tracing.Nr   r  r   r|  rv   r   ry   c                   s8   t  j|||d || _t| j| j| j| j|d| _d S )Nr   r   rv   )r   r   ry   )r\  r  r  r   r  r  r  __ls__gen__r   r   r   rv   ry   ro  r8   r9   r    s   z_TracedStream.__init__r3   r  c                 C  s&   zt | jW S  ty   |    w r   )r  r  r  r  rA  r8   r8   r9   __next__  s   z_TracedStream.__next__c              
   c  sN    z| j E d H  W n ty  } zt| | j|d  d }~ww |   d S Nr   )r  r   r   r  )r   r   r8   r8   r9   r     s   z_TracedStream.__iter__c                 C  s   | j   | S r   )r  rB  rA  r8   r8   r9   rB    s   
z_TracedStream.__enter__c              	   C  sJ   z| j |||W | j|r|d S d d S | j|r |d w d d w r   )r  rC  r  r   r2  exc_valexc_tbr8   r8   r9   rC    s   8z_TracedStream.__exit__NN)r   r  r   r|  rv   r   ry   r   r3   r  )r3   r  )
r   r   r   r   r  r  r   rB  rC  rn  r8   r8   ro  r9   r     s    


r   c                      sX   e Zd ZdZ		dd fd
dZddddZdddZdddZdd Zdd Z	  Z
S ) r   z?A wrapper for asynchronous stream objects that handles tracing.Nr   r  r   r|  rv   r   ry   c                   s>   t  j|||d || _t| j| j| jt | j|d| _	d S )Nr  )r   r   r   r   r   ry   )
r\  r  r  r   r  r  r   r   r  _TracedAsyncStream__ls_genr  ro  r8   r9   r    s   z_TracedAsyncStream.__init__r   r5  c                   s6   t  }ttj| j||dI d H  tt| d S )NrD  )r
   r   r   r   r   r  rf   rS   )r   r   rF  r8   r8   r9   _aend_trace  s   
z_TracedAsyncStream._aend_tracer3   r  c                   s<   zt tt| jI d H W S  ty   |  I d H   w r   )r   r  r   r  r  r  r  rA  r8   r8   r9   	__anext__  s   z_TracedAsyncStream.__anext__c                 C sT   z| j 2 z	3 d H W }|V  q6 W n ty    |  I d H   w |  I d H  d S r   )r  r   r  )r   r   r8   r8   r9   r     s   z_TracedAsyncStream.__aiter__c                   s   | j  I d H  | S r   )r  rH  rA  r8   r8   r9   rH    s   z_TracedAsyncStream.__aenter__c                   s:   z| j |||I d H W |  I d H  S |  I d H  w r   )r  rI  r  r  r8   r8   r9   rI    s    z_TracedAsyncStream.__aexit__r  )r   r  r   r|  rv   r   ry   r   r   r  r  )r3   r  )r   r   r   r   r  r  r  r   rH  rI  rn  r8   r8   ro  r9   r     s    


r   r  c              
   C  sR   | r'|d ur%z|| W S  t y$ } zt| | W  Y d }~S d }~ww | S d S r   )r   r<   r   )r   rv   r   r8   r8   r9   r     s   

r   r   r   c                 C  sR   | j }|r'|jd ur"|jjjtr"|j}|jd ur"|jjjts|| _ d S d S r   )__traceback__tb_nexttb_framef_codeco_filenameendswith_EXCLUDED_FRAME_FNAME)r   tb_r8   r8   r9   r     s   
r   c                  C  s8   t du rz	ddl} da W t S  ty   da Y t S w t S )zCache for otel import check.Nr   TF)r2   opentelemetry.tracers  )opentelemetryr8   r8   r9   _is_otel_available  s   r  c                 C  s   | rt ds	dS t sdS ddlm}m}m}m}m} ddl	m
}m} || j}|| j}	|||	d||j| d}
||
}||S )zCreate OpenTelemetry context manager if OTEL is enabled and available.

    Args:
        run_tree: The current run tree.

    Returns:
        Context manager for use_span or None if not available.
    OTEL_ENABLEDNr   )NonRecordingSpanSpanContext
TraceFlags
TraceStateuse_span)get_otel_span_id_from_uuidget_otel_trace_id_from_uuidF)trace_idspan_id	is_remotetrace_flagstrace_state)r"   is_env_var_truishr  r  r  r  r  r  r  langsmith._internal._otel_utilsr  r  r  re   SAMPLED)r?   r  r  r  r  r  r  r  r  r  span_contextnon_recording_spanr8   r8   r9   r     s"   	

r   )r3   r4   )r,   r   r3   r;   r   )rA   rB   r3   rC   )r*   rT   r+   rU   r,   rV   r)   rW   r-   rX   r   rY   r.   rZ   r/   rT   r[   r   r3   r\   )rj   r   r3   rk   )rj   rz   ru   rT   r,   r{   r+   rU   r   rY   rv   r|   r*   rT   rw   r}   rx   r~   ry   r   r3   r   )rj   r   r3   r   )r?   r   r   r   r[   r   r3   r   )rj   rz   r3   r   rJ  )r   r   ru   rT   r,   r{   r+   rU   r   rY   rv   r|   r*   rT   rw   r}   rx   r~   ry   r   r   r}   r   r   r3   r   )r   r   r[   r   r3   r   )r*   rT   r3   rT   )rP  r   r3   r'   r  )r  r|  r   r  r   r5  r3   r;   )r   ra  r   r   r3   ra  )r   r   r   r   r3   r4   rK  )rj   r   r   r  r   r   r   r   r[   r   r3   r|  )
r  r|  r   r  r   r5  r   r~   r3   r;   )rj   r   r3   r   )r   r  r   r   r[   r   r3   rC   )r   r  rj   r   r3   r   )r   r  rj   r   r3   r  )
r   r  r   r   rj   r   r[   r   r3   r  )rA   rV   )r   r  r   r|  r   r   r   r  ry   r   r   r  r3   r  )r   r  r   r|  r   r   r   r   r   r  ry   r   r   r  r3   r  )r   r  rv   r   r3   r   )r   r   )r3   r   )r?   r4   )zr   
__future__r   r   
contextlibcontextvarsr  ro   r   r  r_   collections.abcr   r   r   r   r   r   r	   r
   typingr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typing_extensionsr   r   r   r   langsmith._internal._context	_internalr5   	langsmithr   r  r    r!   r"   langsmith._internalr#   r   langsmith.envr$   langsmith.run_treesr%   typesr&   rq  r'   	getLoggerr   r<   r6   rK   rL   rM   rN   rO   rP   rQ   r0   r   r  r2   r:   r@   rS   contextmanagerri   get_run_tree_contextrs   r   r   r   r   r   r   r   r   r  r&  rv  r  r|  r  r  r  rb   r   r  rm   r  r  r  r  	lru_cacher  r  r  rf   r   r   r  r  r   r   r   r   r  r   r8   r8   r8   r9   <module>   s$   $	D


F



    =  
 
t
27 





;H<4
<



+
