o
    Jjgw                     @   sB  d Z ddlZddlZddlZddlZddl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ZddlmZ ddlmZmZmZmZmZmZ ddl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, ddl-m.Z. e/e0Z1de2fddZ3G dd de"ee4ef ee4ef f eZ5dS )z0Base interface that all chains should implement.    N)ABCabstractmethod)Path)AnyDictListOptionalTypeUnioncast)
deprecated)AsyncCallbackManagerAsyncCallbackManagerForChainRunBaseCallbackManagerCallbackManagerCallbackManagerForChainRun	Callbacks)
BaseMemory)RunInfo)RunnableConfigRunnableSerializableensure_configrun_in_executor)create_model)	BaseModel
ConfigDictFieldfield_validatormodel_validator)RUN_KEYreturnc                  C   s   ddl m}  |  S )Nr   get_verbose)langchain.globalsr"   r!    r$   M/var/www/html/zoom/venv/lib/python3.10/site-packages/langchain/chains/base.py_get_verbosity+   s   r&   c                       s8  e Zd ZU dZdZee ed< 	 edddZ	e
ed< 	 eedZeed< 	 dZeee  ed	< 	 dZeeeef  ed
< 	 edddZee ed< 	 eddZ	dXdee dee fddZ	dXdee dee fddZ	dXdeeef dee dedeeef fddZ	dXdeeef dee dedeeef fddZedefddZ e!dde"dedefddZ#e$ddde"dee defd d!Z%ee&dee fd"d#Z'ee&dee fd$d%Z(d&eeef ddfd'd(Z)d)eeef ddfd*d+Z*e&	dXd&eeef d,ee+ deeef fd-d.Z,	dXd&eeef d,ee- deeef fd/d0Z.e/d1d2d3d4	5	dYdddd5d6d&e0eeef ef d7ede
d	eee  d
eeeef  d8ee d9edeeef fd:d;Z1e/d1d<d3d4	5	dYdddd5d6d&e0eeef ef d7ede
d	eee  d
eeeef  d8ee d9edeeef fd=d>Z2	5dZd&eeef d)eeef d7edeeef fd?d@Z3	5dZd&eeef d)eeef d7edeeef fdAdBZ4d&e0eeef ef deeef fdCdDZ5d&e0eeef ef deeef fdEdFZ6edefdGdHZ7e/d1d2d3d4ddddIdJede
d	eee  d
eeeef  dedefdKdLZ8e/d1d<d3d4ddddIdJede
d	eee  d
eeeef  dedefdMdNZ9dedef fdOdPZ:dQe0e;ef ddfdRdSZ<e/d1dTd3d4	dXdUeeeef  de
deeeef  fdVdWZ=  Z>S )[Chaina  Abstract base class for creating structured sequences of calls to components.

    Chains should be used to encode a sequence of calls to components like
    models, document retrievers, other chains, etc., and provide a simple interface
    to this sequence.

    The Chain interface makes it easy to create apps that are:
        - Stateful: add Memory to any Chain to give it state,
        - Observable: pass Callbacks to a Chain to execute additional functionality,
            like logging, outside the main sequence of component calls,
        - Composable: the Chain API is flexible enough that it is easy to combine
            Chains with other components, including other Chains.

    The main methods exposed by chains are:
        - `__call__`: Chains are callable. The `__call__` method is the primary way to
            execute a Chain. This takes inputs as a dictionary and returns a
            dictionary output.
        - `run`: A convenience method that takes inputs as args/kwargs and returns the
            output as a string or object. This method can only be used for a subset of
            chains and cannot return as rich of an output as `__call__`.
    NmemoryT)defaultexclude	callbacks)default_factoryverbosetagsmetadatacallback_manager)arbitrary_types_allowedconfigr    c                 C      t 	di dd | jD S )N
ChainInputc                 S      i | ]}|t d fqS Nr   .0kr$   r$   r%   
<dictcomp>q       z*Chain.get_input_schema.<locals>.<dictcomp>)r4   )r   
input_keysselfr2   r$   r$   r%   get_input_schemal   
   zChain.get_input_schemac                 C   r3   )NChainOutputc                 S   r5   r6   r7   r8   r$   r$   r%   r;   y   r<   z+Chain.get_output_schema.<locals>.<dictcomp>)rB   )r   output_keysr>   r$   r$   r%   get_output_schemat   rA   zChain.get_output_schemainputkwargsc              
   K   s*  t |}|d}|d}|d}|dp|  }|d}|dd}	|dd}
| |}t|| j| j|| j|| j	}t
| jjd	}|jd |||d
}z| | |rc| j||dn| |}| |||
}W n ty } z|| |d }~ww || |	rt|jd|t< |S Nr+   r.   r/   run_namerun_idinclude_run_infoFreturn_only_outputsrun_manager)name)rL   )rI   )r   getget_nameprep_inputsr   	configurer+   r-   r.   r/   inspect	signature_call
parameterson_chain_start_validate_inputsprep_outputsBaseExceptionon_chain_erroron_chain_endr   rI   r   r?   rE   r2   rF   r+   r.   r/   rH   rI   rJ   rK   inputsr0   new_arg_supportedrL   outputsfinal_outputser$   r$   r%   invoke|   sV   




	


zChain.invokec              
      sV  t |}|d}|d}|d}|dp|  }|d}|dd}	|dd}
| |I d H }t|| j| j|| j|| j	}t
| jjd	}|jd |||d
I d H }z%| | |rm| j||dI d H n| |I d H }| |||
I d H }W n ty } z
||I d H  |d }~ww ||I d H  |	rt|jd|t< |S rG   )r   rN   rO   aprep_inputsr   rQ   r+   r-   r.   r/   rR   rS   _acallrU   rV   rW   aprep_outputsrY   rZ   r[   r   rI   r   r\   r$   r$   r%   ainvoke   sX   



	
zChain.ainvokec                 C   s   t d)Nz)Saving not supported for this chain type.)NotImplementedErrorr?   r$   r$   r%   _chain_type   s   zChain._chain_typebefore)modevaluesc                 C   sD   | ddur | ddurtdtdt |dd|d< |S )z6Raise deprecation warning if callback_manager is used.r0   Nr+   zCannot specify both callback_manager and callbacks. callback_manager is deprecated, callbacks is the preferred parameter to pass in.z=callback_manager is deprecated. Please use callbacks instead.)rN   
ValueErrorwarningswarnDeprecationWarningpop)clsrl   r$   r$   r%   "raise_callback_manager_deprecation   s   z(Chain.raise_callback_manager_deprecationc                 C   s   |du rt  S |S )zgSet the chain verbosity.

        Defaults to the global setting if not specified by the user.
        N)r&   )rr   r-   r$   r$   r%   set_verbose   s   zChain.set_verbosec                 C      dS )z'Keys expected to be in the chain input.Nr$   rh   r$   r$   r%   r=         zChain.input_keysc                 C   ru   )z(Keys expected to be in the chain output.Nr$   rh   r$   r$   r%   rC     rv   zChain.output_keysr]   c                 C   sn   t |ts$t| j}| jdur|| jj}t|dkr$td| dt| j|}|r5td| dS )z"Check that all inputs are present.N   zMA single string input was passed in, but this chain expects multiple inputs (zt). When a chain expects multiple inputs, please call it by passing in a dictionary, eg `chain({'foo': 1, 'bar': 2})`zMissing some input keys: )	
isinstancedictsetr=   r(   
differencememory_variableslenrm   )r?   r]   _input_keysmissing_keysr$   r$   r%   rW     s   


zChain._validate_inputsr_   c                 C   s&   t | j|}|rtd| d S )NzMissing some output keys: )rz   rC   r{   rm   )r?   r_   r   r$   r$   r%   _validate_outputs$  s   zChain._validate_outputsrL   c                 C   ru   )a  Execute the chain.

        This is a private method that is not user-facing. It is only called within
            `Chain.__call__`, which is the user-facing wrapper method that handles
            callbacks configuration and some input/output processing.

        Args:
            inputs: A dict of named inputs to the chain. Assumed to contain all inputs
                specified in `Chain.input_keys`, including any inputs added by memory.
            run_manager: The callbacks manager that contains the callback handlers for
                this run of the chain.

        Returns:
            A dict of named outputs. Should contain all outputs specified in
                `Chain.output_keys`.
        Nr$   r?   r]   rL   r$   r$   r%   rT   )  rv   zChain._callc                    s$   t d| j||r| ndI dH S )a  Asynchronously execute the chain.

        This is a private method that is not user-facing. It is only called within
            `Chain.acall`, which is the user-facing wrapper method that handles
            callbacks configuration and some input/output processing.

        Args:
            inputs: A dict of named inputs to the chain. Assumed to contain all inputs
                specified in `Chain.input_keys`, including any inputs added by memory.
            run_manager: The callbacks manager that contains the callback handlers for
                this run of the chain.

        Returns:
            A dict of named outputs. Should contain all outputs specified in
                `Chain.output_keys`.
        N)r   rT   get_syncr   r$   r$   r%   rd   @  s   
zChain._acallz0.1.0rb   z1.0)alternativeremovalF)r.   r/   rH   rJ   rK   rH   rJ   c          	      C   s4   ||||d}| j |ttdd | D ||dS )a  Execute the chain.

        Args:
            inputs: Dictionary of inputs, or single input if chain expects
                only one param. Should contain all inputs specified in
                `Chain.input_keys` except for inputs that will be set by the chain's
                memory.
            return_only_outputs: Whether to return only outputs in the
                response. If True, only new keys generated by this chain will be
                returned. If False, both input keys and new keys generated by this
                chain will be returned. Defaults to False.
            callbacks: Callbacks to use for this chain run. These will be called in
                addition to callbacks passed to the chain during construction, but only
                these runtime callbacks will propagate to calls to other objects.
            tags: List of string tags to pass to all callbacks. These will be passed in
                addition to tags passed to the chain during construction, but only
                these runtime tags will propagate to calls to other objects.
            metadata: Optional metadata associated with the chain. Defaults to None
            include_run_info: Whether to include run info in the response. Defaults
                to False.

        Returns:
            A dict of named outputs. Should contain all outputs specified in
                `Chain.output_keys`.
        r+   r.   r/   rH   c                 S   s   i | ]\}}|d ur||qS r6   r$   r9   r:   vr$   r$   r%   r;         z"Chain.__call__.<locals>.<dictcomp>rK   rJ   )rb   r   r   items	r?   r]   rK   r+   r.   r/   rH   rJ   r2   r$   r$   r%   __call__Y  s   &zChain.__call__rf   c          	         s<   ||||d}| j |ttdd | D ||dI dH S )a  Asynchronously execute the chain.

        Args:
            inputs: Dictionary of inputs, or single input if chain expects
                only one param. Should contain all inputs specified in
                `Chain.input_keys` except for inputs that will be set by the chain's
                memory.
            return_only_outputs: Whether to return only outputs in the
                response. If True, only new keys generated by this chain will be
                returned. If False, both input keys and new keys generated by this
                chain will be returned. Defaults to False.
            callbacks: Callbacks to use for this chain run. These will be called in
                addition to callbacks passed to the chain during construction, but only
                these runtime callbacks will propagate to calls to other objects.
            tags: List of string tags to pass to all callbacks. These will be passed in
                addition to tags passed to the chain during construction, but only
                these runtime tags will propagate to calls to other objects.
            metadata: Optional metadata associated with the chain. Defaults to None
            include_run_info: Whether to include run info in the response. Defaults
                to False.

        Returns:
            A dict of named outputs. Should contain all outputs specified in
                `Chain.output_keys`.
        r   c                 S   s   i | ]\}}|d ur||qS r6   r$   r   r$   r$   r%   r;     r   zChain.acall.<locals>.<dictcomp>r   N)rf   r   r   r   r   r$   r$   r%   acall  s   &zChain.acallc                 C   s6   |  | | jdur| j|| |r|S i ||S a  Validate and prepare chain outputs, and save info about this run to memory.

        Args:
            inputs: Dictionary of chain inputs, including any inputs added by chain
                memory.
            outputs: Dictionary of initial chain outputs.
            return_only_outputs: Whether to only return the chain outputs. If False,
                inputs are also added to the final outputs.

        Returns:
            A dict of the final chain outputs.
        N)r   r(   save_contextr?   r]   r_   rK   r$   r$   r%   rX     s   

zChain.prep_outputsc                    s>   |  | | jdur| j||I dH  |r|S i ||S r   )r   r(   asave_contextr   r$   r$   r%   re     s   

zChain.aprep_outputsc                 C   sf   t |tst| j}| jdur|| jj}t|d |i}| jdur1| j|}t|fi |}|S a  Prepare chain inputs, including adding inputs from memory.

        Args:
            inputs: Dictionary of raw inputs, or single input if chain expects
                only one param. Should contain all inputs specified in
                `Chain.input_keys` except for inputs that will be set by the chain's
                memory.

        Returns:
            A dictionary of all inputs, including those added by the chain's memory.
        Nr   )	rx   ry   rz   r=   r(   r{   r|   listload_memory_variablesr?   r]   r~   external_contextr$   r$   r%   rP     s   



zChain.prep_inputsc                    sn   t |tst| j}| jdur|| jj}t|d |i}| jdur5| j|I dH }t|fi |}|S r   )	rx   ry   rz   r=   r(   r{   r|   r   aload_memory_variablesr   r$   r$   r%   rc   
  s   



zChain.aprep_inputsc                 C   s*   t | jdkrtd| j d| jd S )Nrw   B`run` not supported when there is not exactly one output key. Got .r   )r}   rC   rm   rh   r$   r$   r%   _run_output_key"  s   
zChain._run_output_keyr+   r.   r/   argsc                O   s|   | j }|r|st|dkrtd| |d |||d| S |r+|s+| ||||d| S |s3|s3tdtd| d| d)	a  Convenience method for executing chain.

        The main difference between this method and `Chain.__call__` is that this
        method expects inputs to be passed directly in as positional arguments or
        keyword arguments, whereas `Chain.__call__` expects a single input dictionary
        with all the inputs

        Args:
            *args: If the chain expects a single input, it can be passed in as the
                sole positional argument.
            callbacks: Callbacks to use for this chain run. These will be called in
                addition to callbacks passed to the chain during construction, but only
                these runtime callbacks will propagate to calls to other objects.
            tags: List of string tags to pass to all callbacks. These will be passed in
                addition to tags passed to the chain during construction, but only
                these runtime tags will propagate to calls to other objects.
            **kwargs: If the chain expects multiple inputs, they can be passed in
                directly as keyword arguments.

        Returns:
            The chain output.

        Example:
            .. code-block:: python

                # Suppose we have a single-input chain that takes a 'question' string:
                chain.run("What's the temperature in Boise, Idaho?")
                # -> "The temperature in Boise is..."

                # Suppose we have a multi-input chain that takes a 'question' string
                # and 'context' string:
                question = "What's the temperature in Boise, Idaho?"
                context = "Weather report for Boise, Idaho on 07/03/23..."
                chain.run(question=question, context=context)
                # -> "The temperature in Boise is..."
        rw   ,`run` supports only one positional argument.r   r   z^`run` supported with either positional arguments or keyword arguments, but none were provided.^`run` supported with either positional arguments or keyword arguments but not both. Got args:  and kwargs: r   )r   r}   rm   )r?   r+   r.   r/   r   rF   _output_keyr$   r$   r%   run+  s,   .z	Chain.runc                   s   t | jdkrtd| j d|r2|s2t |dkrtd| j|d |||dI dH | jd  S |rG|sG| j||||dI dH | jd  S td| d	| d)
a  Convenience method for executing chain.

        The main difference between this method and `Chain.__call__` is that this
        method expects inputs to be passed directly in as positional arguments or
        keyword arguments, whereas `Chain.__call__` expects a single input dictionary
        with all the inputs


        Args:
            *args: If the chain expects a single input, it can be passed in as the
                sole positional argument.
            callbacks: Callbacks to use for this chain run. These will be called in
                addition to callbacks passed to the chain during construction, but only
                these runtime callbacks will propagate to calls to other objects.
            tags: List of string tags to pass to all callbacks. These will be passed in
                addition to tags passed to the chain during construction, but only
                these runtime tags will propagate to calls to other objects.
            **kwargs: If the chain expects multiple inputs, they can be passed in
                directly as keyword arguments.

        Returns:
            The chain output.

        Example:
            .. code-block:: python

                # Suppose we have a single-input chain that takes a 'question' string:
                await chain.arun("What's the temperature in Boise, Idaho?")
                # -> "The temperature in Boise is..."

                # Suppose we have a multi-input chain that takes a 'question' string
                # and 'context' string:
                question = "What's the temperature in Boise, Idaho?"
                context = "Weather report for Boise, Idaho on 07/03/23..."
                await chain.arun(question=question, context=context)
                # -> "The temperature in Boise is..."
        rw   r   r   r   r   r   Nr   r   )r}   rC   rm   r   )r?   r+   r.   r/   r   rF   r$   r$   r%   arunr  s8   .

z
Chain.arunc                    s8   t  jdi |}z| j|d< W |S  ty   Y |S w )a  Dictionary representation of chain.

        Expects `Chain._chain_type` property to be implemented and for memory to be
            null.

        Args:
            **kwargs: Keyword arguments passed to default `pydantic.BaseModel.dict`
                method.

        Returns:
            A dictionary representation of the chain.

        Example:
            .. code-block:: python

                chain.dict(exclude_unset=True)
                # -> {"_type": "foo", "verbose": False, ...}
        _typeNr$   )superry   ri   rg   )r?   rF   _dict	__class__r$   r%   ry     s   z
Chain.dict	file_pathc                 C   s  | j dur	td|  }d|vrtd|  dt|tr#t|}n|}|j}|jddd |j	dkrTt
|d	}tj||d
d W d   dS 1 sMw   Y  dS |j	drzt
|d	}tj||dd W d   dS 1 ssw   Y  dS t| d)a6  Save the chain.

        Expects `Chain._chain_type` property to be implemented and for memory to be
            null.

        Args:
            file_path: Path to file to save the chain to.

        Example:
            .. code-block:: python

                chain.save(file_path="path/chain.yaml")
        Nz&Saving of memory is not yet supported.r   zChain z does not support saving.T)parentsexist_okz.jsonw   )indent)z.yamlz.ymlF)default_flow_stylez must be json or yaml)r(   rm   ry   rg   rx   strr   parentmkdirsuffixopenjsondumpendswithyaml)r?   r   
chain_dict	save_pathdirectory_pathfr$   r$   r%   save  s&   



""z
Chain.savebatch
input_listc                    s    fdd|D S )z)Call the chain on all inputs in the list.c                    s   g | ]}| d qS ))r+   r$   )r9   r]   r+   r?   r$   r%   
<listcomp>  s    zChain.apply.<locals>.<listcomp>r$   )r?   r   r+   r$   r   r%   apply  s   zChain.applyr6   )FN)F)?__name__
__module____qualname____doc__r(   r   r   __annotations__r   r+   r   r&   r-   boolr.   r   r   r/   r   r   r0   r   r   model_configr   r	   r   r@   rD   rb   rf   propertyri   r   classmethodrs   r   rt   r   r=   rC   rW   r   r   rT   r   rd   r   r
   r   r   rX   re   rP   rc   r   r   r   ry   r   r   r   __classcell__r$   r$   r   r%   r'   1   s  
 
	



8


3







	

2
	

5







**
F
G(r'   )6r   rR   r   loggingrn   abcr   r   pathlibr   typingr   r   r   r   r	   r
   r   r   langchain_core._apir   langchain_core.callbacksr   r   r   r   r   r   langchain_core.memoryr   langchain_core.outputsr   langchain_core.runnablesr   r   r   r   langchain_core.runnables.utilsr   pydanticr   r   r   r   r   langchain.schemar   	getLoggerr   loggerr   r&   r   r'   r$   r$   r$   r%   <module>   s(    $ 
.