
    Ng[                        d Z ddlZddl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 ddlmZ ddlmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZm Z  ddl!m"Z" dddddZ#dede$fdZ%dede	e$e&f         fdZ'dede&de&fdZ(dedee$         fdZ)dedee$ef         fdZ*deee$ef         e
e         ef         dee$ef         fdZ+deeee$ef         e
e         ef                  deeef         fdZ,dddeeee$ef         e
e         ef                  dededeeeef                  d edefd!Z-ddd"eee$ef         e
e         f         dededeeeef                  d edefd#Z.	 ddd$deeee$ef         e
e         ef                  deded%e$dee         d edefd&Z/ddd$d"eee$ef         e
e         f         deded%e$dee         d edefd'Z0dS )(zAMethods for creating chains that use Ernie function-calling APIs.    N)
AnyCallableDictListOptionalSequenceTupleTypeUnioncast)LLMChain)BaseLanguageModel)BaseGenerationOutputParserBaseLLMOutputParserBaseOutputParser)BasePromptTemplate)Runnable)is_basemodel_subclass)	BaseModel)JsonOutputFunctionsParser!PydanticAttrOutputFunctionsParserPydanticOutputFunctionsParser)"convert_pydantic_to_ernie_functionstringnumberboolean)strintfloatboolfunctionreturnc                     | j         S )z"Get the name of a Python function.)__name__r!   s    k/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chains/ernie_functions/base.py_get_python_function_namer'   ,   s        c                    t          j        |           }|r|                    d          }g }d}d}|D ]`}|                    d          r|} nF|                    d          s|                    d          rd}H|s|                    |           `ad                    |          }nd	}d}i }|rd}	|                    d
          dd         D ]}
d|
v rB|
                    d          \  }	}|                                ||	                                <   H|	r7||	                                xx         d|
                                z   z  cc<   ||fS )zParse the function and argument descriptions from the docstring of a function.

    Assumes the function docstring follows Google Python style guide.
    z

NFzArgs:zReturns:zExample:T  
   :)inspectgetdocsplit
startswithappendjoinstrip)r!   	docstringdocstring_blocksdescriptors
args_blockpast_descriptorsblockdescriptionarg_descriptionsarglinedescs               r&    _parse_python_function_docstringrA   1   s   
 x((I $??622
 % 
	 
	E(( 	"
!!*-- 1A1A*1M1M #'  % ""5))))hh{++
 D$$T**122. 	D 	DDd{{ JJsOO	T04

 -- D ---tzz||1CC---(((r(   r=   c                 |   i }t          j        |           j        }|                                D ]\  }}|dk    rt	          |t
                    r't          |          r|                                ||<   n%|j        t          v rdt          |j                 i||<   ||v r||vri ||<   ||         ||         d<   |S )zGet JsonSchema describing a Python functions arguments.

    Assumes all function arguments are of primitive types (int, float, str, bool) or
    are subclasses of pydantic.BaseModel.
    r"   typer<   )
r/   getfullargspecannotationsitems
isinstancerC   r   schemar$   PYTHON_TO_JSON_TYPES)r!   r=   
propertiesrE   r>   arg_types         r&   _get_python_function_argumentsrL   W   s     J(22>K$**,, C CX(??h%% 	P*?*I*I 	P 'oo//JsOO"666%';H<M'NOJsO"""*$$"$
3-=c-BJsOM*r(   c                    t          j        |           j        r"j        dt	          j                            nj        }|fdj        D             z  }t          |           t          u }|r|d         dk    r
|dd         }|S )z1Get the required arguments for a Python function.Nc                 *    g | ]}|j         pi v|S  )kwonlydefaults).0kspecs     r&   
<listcomp>z6_get_python_function_required_args.<locals>.<listcomp>s   s,    TTTqq9L9RPR/S/S/S/S/Sr(   r   selfr-   )r/   rD   defaultsargslen
kwonlyargsrC   )r!   requiredis_classrS   s      @r&   "_get_python_function_required_argsr\   o   s    !(++D37=Oty.C....//diHTTTTDOTTTTHH~~%H  HQK6))ABB<Or(   c                     t          |           \  }}t          |           |dt          | |          t          |           ddS )a  Convert a Python function to an Ernie function-calling API compatible dict.

    Assumes the Python function has type hints and a docstring with a description. If
        the docstring has Google Python style argument descriptions, these will be
        included as well.
    object)rC   rJ   rZ   namer<   
parameters)rA   r'   rL   r\   )r!   r<   r=   s      r&   )convert_python_function_to_ernie_functionrb   {   s[     %EX$N$N!K!)(33"8CSTT:8DD
 
  r(   c                 8   t          | t                    r| S t          | t                    r1t          |           r"t	          t
          t          |                     S t          |           rt          |           S t          dt          |            d          )a  Convert a raw function/class to an Ernie function.

    Args:
        function: Either a dictionary, a pydantic.BaseModel class, or a Python function.
            If a dictionary is passed in, it is assumed to already be a valid Ernie
            function.

    Returns:
        A dict version of the passed in function which is compatible with the
            Ernie function-calling API.
    zUnsupported function type zG. Functions must be passed in as Dict, pydantic.BaseModel, or Callable.)
rG   dictrC   r   r   r   r   callablerb   
ValueErrorr%   s    r&   convert_to_ernie_functionrg      s     (D!! 
	Hd	#	# 	
(=h(G(G 	
D<XFFGGG	(		 
8BBB :h : : :
 
 	
r(   	functionsc                 N   d | D             }t          | d         t                    r\t          | d                   rGt          |           dk    rd t	          ||           D             }n| d         }t          |          }n!t          t          |           dk              }|S )au  Get the appropriate function output parser given the user functions.

    Args:
        functions: Sequence where element is a dictionary, a pydantic.BaseModel class,
            or a Python function. If a dictionary is passed in, it is assumed to
            already be a valid Ernie function.

    Returns:
        A PydanticOutputFunctionsParser if functions are Pydantic classes, otherwise
            a JsonOutputFunctionsParser. If there's only one function and it is
            not a Pydantic class, then the output parser will automatically extract
            only the function arguments and not the function name.
    c                 8    g | ]}t          |          d          S )r`   rg   rQ   fs     r&   rT   z+get_ernie_output_parser.<locals>.<listcomp>   s&    NNNq/226:NNNr(   r   r-   c                     i | ]\  }}||	S rO   rO   )rQ   r`   fns      r&   
<dictcomp>z+get_ernie_output_parser.<locals>.<dictcomp>   s+     = = =%T2b= = =r(   )pydantic_schema)	args_only)rG   rC   r   rX   zipr   r   )rh   function_namesrq   output_parsers       r&   get_ernie_output_parserrv      s      ONINNNN)A,%% Q*?	!*M*M Qy>>A= =),^Y)G)G= = =OO (lO)/JJJ 	 2C	NNa<OPPPr(   )ru   llmpromptru   kwargsc                    | st          d          d | D             }d|i|}t          |          dk    rd|d         d         i|d<   |pt          |           }| |j        di |z  |z  S )	a  Create a runnable sequence that uses Ernie functions.

    Args:
        functions: A sequence of either dictionaries, pydantic.BaseModels classes, or
            Python functions. If dictionaries are passed in, they are assumed to
            already be a valid Ernie functions. If only a single
            function is passed in, then it will be enforced that the model use that
            function. pydantic.BaseModels and Python functions should have docstrings
            describing what the function does. For best results, pydantic.BaseModels
            should have descriptions of the parameters and Python functions should have
            Google Python style args descriptions in the docstring. Additionally,
            Python functions should only use primitive types (str, int, float, bool) or
            pydantic.BaseModels for arguments.
        llm: Language model to use, assumed to support the Ernie function-calling API.
        prompt: BasePromptTemplate to pass to the model.
        output_parser: BaseLLMOutputParser to use for parsing model outputs. By default
            will be inferred from the function types. If pydantic.BaseModels are passed
            in, then the OutputParser will try to parse outputs using those. Otherwise
            model outputs will simply be parsed as JSON. If multiple functions are
            passed in and they are not pydantic.BaseModels, the chain output will
            include both the name of the function that was returned and the arguments
            to pass to the function.

    Returns:
        A runnable sequence that will pass in the given functions to the model when run.

    Example:
        .. code-block:: python

                from typing import Optional

                from langchain.chains.ernie_functions import create_ernie_fn_chain
                from langchain_community.chat_models import ErnieBotChat
                from langchain_core.prompts import ChatPromptTemplate
                from pydantic import BaseModel, Field


                class RecordPerson(BaseModel):
                    """Record some identifying information about a person."""

                    name: str = Field(..., description="The person's name")
                    age: int = Field(..., description="The person's age")
                    fav_food: Optional[str] = Field(None, description="The person's favorite food")


                class RecordDog(BaseModel):
                    """Record some identifying information about a dog."""

                    name: str = Field(..., description="The dog's name")
                    color: str = Field(..., description="The dog's color")
                    fav_food: Optional[str] = Field(None, description="The dog's favorite food")


                llm = ErnieBotChat(model_name="ERNIE-Bot-4")
                prompt = ChatPromptTemplate.from_messages(
                    [
                        ("user", "Make calls to the relevant function to record the entities in the following input: {input}"),
                        ("assistant", "OK!"),
                        ("user", "Tip: Make sure to answer in the correct format"),
                    ]
                )
                chain = create_ernie_fn_runnable([RecordPerson, RecordDog], llm, prompt)
                chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
                # -> RecordDog(name="Harry", color="brown", fav_food="chicken")
    5Need to pass in at least one function. Received zero.c                 ,    g | ]}t          |          S rO   rk   rl   s     r&   rT   z,create_ernie_fn_runnable.<locals>.<listcomp>  !    GGG033GGGr(   rh   r-   r`   r   function_callrO   )rf   rX   rv   bind)rh   rw   rx   ru   ry   ernie_functions
llm_kwargss          r&   create_ernie_fn_runnabler      s    R  RPQQQGGYGGGO"-!I&!IJ
?q  '-q/A&/I&J
?#!G%<Y%G%GMHCH**z***]::r(   output_schemac                     t           t                    rdd d}n* G  fddt                    }|}|pt          |d          }t	          |g||fd|i|S )	a  Create a runnable that uses an Ernie function to get a structured output.

    Args:
        output_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary
            is passed in, it's assumed to already be a valid JsonSchema.
            For best results, pydantic.BaseModels should have docstrings describing what
            the schema represents and descriptions for the parameters.
        llm: Language model to use, assumed to support the Ernie function-calling API.
        prompt: BasePromptTemplate to pass to the model.
        output_parser: BaseLLMOutputParser to use for parsing model outputs. By default
            will be inferred from the function types. If pydantic.BaseModels are passed
            in, then the OutputParser will try to parse outputs using those. Otherwise
            model outputs will simply be parsed as JSON.

    Returns:
        A runnable sequence that will pass the given function to the model when run.

    Example:
        .. code-block:: python

            from typing import Optional

            from langchain.chains.ernie_functions import create_structured_output_chain
            from langchain_community.chat_models import ErnieBotChat
            from langchain_core.prompts import ChatPromptTemplate
            from pydantic import BaseModel, Field

            class Dog(BaseModel):
                """Identifying information about a dog."""

                name: str = Field(..., description="The dog's name")
                color: str = Field(..., description="The dog's color")
                fav_food: Optional[str] = Field(None, description="The dog's favorite food")

            llm = ErnieBotChat(model_name="ERNIE-Bot-4")
            prompt = ChatPromptTemplate.from_messages(
                [
                    ("user", "Use the given format to extract information from the following input: {input}"),
                    ("assistant", "OK!"),
                    ("user", "Tip: Make sure to answer in the correct format"),
                ]
            )
            chain = create_structured_output_chain(Dog, llm, prompt)
            chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
            # -> Dog(name="Harry", color="brown", fav_food="chicken")
    output_formatterLOutput formatter. Should always be used to format your response to the user.r_   c                        e Zd ZU dZ ed<   dS );create_structured_output_runnable.<locals>._OutputFormatterr   outputNr$   
__module____qualname____doc____annotations__r   s   r&   _OutputFormatterr   `  %         ^^!!!!!!r(   r   r   rq   	attr_nameru   )rG   rd   r   r   r   )r   rw   rx   ru   ry   r!   r   s   `      r&   !create_structured_output_runnabler     s    l -&& 
& (
 
	" 	" 	" 	" 	" 	" 	"y 	" 	" 	"
 $% 
)J,*
 *
 *
 $	
  $	
   r(   
output_keyru   r   c          	          | st          d          d | D             }|pt          |           }d|i}t          |          dk    rd|d         d         i|d<   t          d	|||||d|}|S )
a  [Legacy] Create an LLM chain that uses Ernie functions.

    Args:
        functions: A sequence of either dictionaries, pydantic.BaseModels classes, or
            Python functions. If dictionaries are passed in, they are assumed to
            already be a valid Ernie functions. If only a single
            function is passed in, then it will be enforced that the model use that
            function. pydantic.BaseModels and Python functions should have docstrings
            describing what the function does. For best results, pydantic.BaseModels
            should have descriptions of the parameters and Python functions should have
            Google Python style args descriptions in the docstring. Additionally,
            Python functions should only use primitive types (str, int, float, bool) or
            pydantic.BaseModels for arguments.
        llm: Language model to use, assumed to support the Ernie function-calling API.
        prompt: BasePromptTemplate to pass to the model.
        output_key: The key to use when returning the output in LLMChain.__call__.
        output_parser: BaseLLMOutputParser to use for parsing model outputs. By default
            will be inferred from the function types. If pydantic.BaseModels are passed
            in, then the OutputParser will try to parse outputs using those. Otherwise
            model outputs will simply be parsed as JSON. If multiple functions are
            passed in and they are not pydantic.BaseModels, the chain output will
            include both the name of the function that was returned and the arguments
            to pass to the function.

    Returns:
        An LLMChain that will pass in the given functions to the model when run.

    Example:
        .. code-block:: python

                from typing import Optional

                from langchain.chains.ernie_functions import create_ernie_fn_chain
                from langchain_community.chat_models import ErnieBotChat
                from langchain_core.prompts import ChatPromptTemplate

                from pydantic import BaseModel, Field


                class RecordPerson(BaseModel):
                    """Record some identifying information about a person."""

                    name: str = Field(..., description="The person's name")
                    age: int = Field(..., description="The person's age")
                    fav_food: Optional[str] = Field(None, description="The person's favorite food")


                class RecordDog(BaseModel):
                    """Record some identifying information about a dog."""

                    name: str = Field(..., description="The dog's name")
                    color: str = Field(..., description="The dog's color")
                    fav_food: Optional[str] = Field(None, description="The dog's favorite food")


                llm = ErnieBotChat(model_name="ERNIE-Bot-4")
                prompt = ChatPromptTemplate.from_messages(
                    [
                        ("user", "Make calls to the relevant function to record the entities in the following input: {input}"),
                        ("assistant", "OK!"),
                        ("user", "Tip: Make sure to answer in the correct format"),
                    ]
                )
                chain = create_ernie_fn_chain([RecordPerson, RecordDog], llm, prompt)
                chain.run("Harry was a chubby brown beagle who loved chicken")
                # -> RecordDog(name="Harry", color="brown", fav_food="chicken")
    r{   c                 ,    g | ]}t          |          S rO   rk   rl   s     r&   rT   z)create_ernie_fn_chain.<locals>.<listcomp>  r}   r(   rh   r-   r`   r   r~   )rw   rx   ru   r   r   rO   )rf   rv   rX   r   )	rh   rw   rx   r   ru   ry   r   r   	llm_chains	            r&   create_ernie_fn_chainr   u  s    X  RPQQQGGYGGGO!G%<Y%G%GM_"J ?q  '-q/A&/I&J
?# #   I r(   c                     t           t                    rdd d}n* G  fddt                    }|}|pt          |d          }t	          |g||f||d|S )	a	  [Legacy] Create an LLMChain that uses an Ernie function to get a structured output.

    Args:
        output_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary
            is passed in, it's assumed to already be a valid JsonSchema.
            For best results, pydantic.BaseModels should have docstrings describing what
            the schema represents and descriptions for the parameters.
        llm: Language model to use, assumed to support the Ernie function-calling API.
        prompt: BasePromptTemplate to pass to the model.
        output_key: The key to use when returning the output in LLMChain.__call__.
        output_parser: BaseLLMOutputParser to use for parsing model outputs. By default
            will be inferred from the function types. If pydantic.BaseModels are passed
            in, then the OutputParser will try to parse outputs using those. Otherwise
            model outputs will simply be parsed as JSON.

    Returns:
        An LLMChain that will pass the given function to the model.

    Example:
        .. code-block:: python

                from typing import Optional

                from langchain.chains.ernie_functions import create_structured_output_chain
                from langchain_community.chat_models import ErnieBotChat
                from langchain_core.prompts import ChatPromptTemplate

                from pydantic import BaseModel, Field

                class Dog(BaseModel):
                    """Identifying information about a dog."""

                    name: str = Field(..., description="The dog's name")
                    color: str = Field(..., description="The dog's color")
                    fav_food: Optional[str] = Field(None, description="The dog's favorite food")

                llm = ErnieBotChat(model_name="ERNIE-Bot-4")
                prompt = ChatPromptTemplate.from_messages(
                    [
                        ("user", "Use the given format to extract information from the following input: {input}"),
                        ("assistant", "OK!"),
                        ("user", "Tip: Make sure to answer in the correct format"),
                    ]
                )
                chain = create_structured_output_chain(Dog, llm, prompt)
                chain.run("Harry was a chubby brown beagle who loved chicken")
                # -> Dog(name="Harry", color="brown", fav_food="chicken")
    r   r   r_   c                        e Zd ZU dZ ed<   dS )8create_structured_output_chain.<locals>._OutputFormatterr   r   Nr   r   s   r&   r   r     r   r(   r   r   r   r   )rG   rd   r   r   r   )r   rw   rx   r   ru   ry   r!   r   s   `       r&   create_structured_output_chainr     s    r -&& 
& (
 
	" 	" 	" 	" 	" 	" 	"y 	" 	" 	"
 $% 
)J,*
 *
 *
 !	
 #    r(   )1r   r/   typingr   r   r   r   r   r   r	   r
   r   r   langchain.chainsr   langchain_core.language_modelsr   langchain_core.output_parsersr   r   r   langchain_core.promptsr   langchain_core.runnablesr   langchain_core.utils.pydanticr   pydanticr   2langchain_community.output_parsers.ernie_functionsr   r   r   )langchain_community.utils.ernie_functionsr   rI   r   r'   rd   rA   rL   r\   rb   rg   rv   r   r   r   r   rO   r(   r&   <module>r      sP   G G                         & % % % % % < < < < < <         
 6 5 5 5 5 5 - - - - - - ? ? ? ? ? ?               
 Y X X X X X 	   S    
#)x #)E#t)<L #) #) #) #)LX  RV    0	 	d3i 	 	 	 		#s(^   *
DcNDOX=>
	#s(^
 
 
 
8d38nd9oxGHI
778   J TXP; P; P;d38nd9oxGHIP;	P; P;
 E"24N"NOPP; P; P; P; P; P;p TXP P Pc3hi89P	P P
 E"24N"NOPP P P P P Pf  !37] ] ]d38nd9oxGHI]	] ]
 ] /0] ] ] ] ] ]J !37T T Tc3hi89T	T T
 T /0T T T T T T T Tr(   