a
    •˜ëjŸ5  ã                   @   s<  d 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
mZ ddlmZmZ ddlmZ ddlmZ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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( ddl)m*Z* ddl+m,Z, e-ƒ Z.edddd�G dd„ de(ƒƒZ/eee  eedœdd„Z0dS )zHModule implements an agent that uses OpenAI's APIs function enabled API.é    )ÚSequence)ÚAnyÚOptionalÚUnion)Ú
deprecated)ÚAgentActionÚAgentFinish)ÚBaseCallbackManagerÚ	Callbacks)ÚBaseLanguageModel)ÚBaseMessageÚSystemMessage)ÚBasePromptTemplate)ÚChatPromptTemplateÚHumanMessagePromptTemplateÚMessagesPlaceholder)ÚBaseMessagePromptTemplate)ÚRunnableÚRunnablePassthrough)ÚBaseTool©Úconvert_to_openai_function)Úmodel_validator)ÚSelf)ÚBaseSingleActionAgent©Ú"format_to_openai_function_messages)Ú OpenAIFunctionsAgentOutputParserz0.1.0Úcreate_openai_functions_agentz1.0)ÚalternativeZremovalc                
   @   sl  e Zd ZU dZeed< ee ed< eed< e	Z
ee	 ed< ee dœdd„Zed	d
�edœdd„ƒZeee dœdd„ƒZeee dœdd„ƒZd"eeeef  eeeeeef dœdd„Zd#eeeef  eeeeef dœdd„Zeeeeef  eedœdd„Ze e!dfe"e# e"ee$  e%dœdd„ƒZ&e dde!feee e"e' e"ee$  e"e# ee(dœd d!„ƒZ)dS )$ÚOpenAIFunctionsAgentaz  An Agent driven by OpenAIs function powered API.

    Args:
        llm: This should be an instance of ChatOpenAI, specifically a model
            that supports using `functions`.
        tools: The tools this agent has access to.
        prompt: The prompt for this agent, should support agent_scratchpad as one
            of the variables. For an easy way to construct this prompt, use
            `OpenAIFunctionsAgent.create_prompt(...)`
        output_parser: The output parser for this agent. Should be an instance of
            OpenAIFunctionsAgentOutputParser.
            Defaults to OpenAIFunctionsAgentOutputParser.
    ÚllmÚtoolsÚpromptÚoutput_parser)Úreturnc                 C   s   dd„ | j D ƒS )zGet allowed tools.c                 S   s   g | ]
}|j ‘qS © )Úname©Ú.0Útr&   r&   úk/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain/agents/openai_functions_agent/base.pyÚ
<listcomp>?   ó    z:OpenAIFunctionsAgent.get_allowed_tools.<locals>.<listcomp>©r"   ©Úselfr&   r&   r+   Úget_allowed_tools=   s    z&OpenAIFunctionsAgent.get_allowed_toolsÚafter)Úmodec                 C   s(   | j }d|jvr$d|j› �}t|ƒ‚| S )zÕValidate prompt.

        Args:
            values: Values to validate.

        Returns:
            Validated values.

        Raises:
            ValueError: If `agent_scratchpad` is not in the prompt.
        Úagent_scratchpadzE`agent_scratchpad` should be one of the variables in the prompt, got )r#   Úinput_variablesÚ
ValueError)r0   r#   Úmsgr&   r&   r+   Úvalidate_promptA   s    
ÿÿz$OpenAIFunctionsAgent.validate_promptc                 C   s   dgS )z0Get input keys. Input refers to user input here.Úinputr&   r/   r&   r&   r+   Ú
input_keysW   s    zOpenAIFunctionsAgent.input_keysc                 C   s   dd„ | j D ƒS )zGet functions.c                 S   s   g | ]}t t|ƒƒ‘qS r&   )Údictr   r(   r&   r&   r+   r,   _   r-   z2OpenAIFunctionsAgent.functions.<locals>.<listcomp>r.   r/   r&   r&   r+   Ú	functions\   s    zOpenAIFunctionsAgent.functionsNT)Úintermediate_stepsÚ	callbacksÚwith_functionsÚkwargsr%   c                    s„   t |ƒ}‡ fdd„| jjD ƒ}tf i |¤d|i¤Ž}| jjf i |¤Ž}| ¡ }	|rh| jj|	| j|d�}
n| jj|	|d�}
| j	 
|
¡S )a
  Given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            callbacks: Callbacks to use. Defaults to None.
            with_functions: Whether to use functions. Defaults to True.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
            If the agent is finished, returns an AgentFinish.
            If the agent is not finished, returns an AgentAction.
        c                    s   i | ]}|d kr|ˆ | “qS ©r4   r&   ©r)   Úk©r@   r&   r+   Ú
<dictcomp>w   s   z-OpenAIFunctionsAgent.plan.<locals>.<dictcomp>r4   ©r<   r>   )r>   )r   r#   r5   r;   Úformat_promptÚto_messagesr!   Zpredict_messagesr<   r$   Úparse_ai_message)r0   r=   r>   r?   r@   r4   Úselected_inputsÚfull_inputsr#   ÚmessagesÚpredicted_messager&   rD   r+   Úplana   s$    
ÿýþzOpenAIFunctionsAgent.plan)r=   r>   r@   r%   c           
      ‹   st   t |ƒ}‡ fdd„| jjD ƒ}tf i |¤d|i¤Ž}| jjf i |¤Ž}| ¡ }| jj|| j|d�I dH }	| j	 
|	¡S )aÈ  Async given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            callbacks: Callbacks to use. Defaults to None.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
            If the agent is finished, returns an AgentFinish.
            If the agent is not finished, returns an AgentAction.
        c                    s   i | ]}|d kr|ˆ | “qS rA   r&   rB   rD   r&   r+   rE   ž   s   z.OpenAIFunctionsAgent.aplan.<locals>.<dictcomp>r4   rF   N)r   r#   r5   r;   rG   rH   r!   Zapredict_messagesr<   r$   rI   )
r0   r=   r>   r@   r4   rJ   rK   r#   rL   rM   r&   rD   r+   ÚaplanŠ   s    
ÿýzOpenAIFunctionsAgent.aplan)Úearly_stopping_methodr=   r@   r%   c                 K   sj   |dkrt ddidƒS |dkrT| j|fddi|¤Ž}t|t ƒrB|S d|› �}t|ƒ‚d	|› �}t|ƒ‚d
S )aÆ  Return response when agent has been stopped due to max iterations.

        Args:
            early_stopping_method: The early stopping method to use.
            intermediate_steps: Intermediate steps.
            **kwargs: User inputs.

        Returns:
            AgentFinish.

        Raises:
            ValueError: If `early_stopping_method` is not `force` or `generate`.
            ValueError: If `agent_decision` is not an AgentAction.
        ÚforceÚoutputz3Agent stopped due to iteration limit or time limit.Ú Úgenerater?   Fz,got AgentAction with no functions provided: zBearly_stopping_method should be one of `force` or `generate`, got N)r   rN   Ú
isinstancer6   )r0   rP   r=   r@   Zagent_decisionr7   r&   r&   r+   Úreturn_stopped_response«   s,    þÿþý

ÿÿz,OpenAIFunctionsAgent.return_stopped_response)Úsystem_messageÚextra_prompt_messagesr%   c                 C   sX   |pg }|t ur|ntdd�}|r(|gng }| g |¢t d¡‘tdd�‘¡ t|d�S )a€  Create prompt for this agent.

        Args:
            system_message: Message to use as the system message that will be the
                first in the prompt.
            extra_prompt_messages: Prompt messages that will be placed between the
                system message and the new human input.

        Returns:
            A prompt template to pass into this agent.
        úYou are a helpful AI assistant.©Úcontentz{input}r4   )Zvariable_name)rL   )Ú_NOT_SETr   Úextendr   Zfrom_templater   r   )ÚclsrW   rX   Z_promptsÚsystem_message_rL   r&   r&   r+   Úcreate_promptÖ   s     ÿýÿþýÿz"OpenAIFunctionsAgent.create_prompt)r!   r"   Úcallback_managerrX   rW   r@   r%   c           	      K   s<   |t ur|ntdd�}| j||d�}| f ||||dœ|¤ŽS )aá  Construct an agent from an LLM and tools.

        Args:
            llm: The LLM to use as the agent.
            tools: The tools to use.
            callback_manager: The callback manager to use. Defaults to None.
            extra_prompt_messages: Extra prompt messages to use. Defaults to None.
            system_message: The system message to use.
                Defaults to a default system message.
            kwargs: Additional parameters to pass to the agent.
        rY   rZ   )rX   rW   )r!   r#   r"   ra   )r\   r   r`   )	r^   r!   r"   ra   rX   rW   r@   r_   r#   r&   r&   r+   Úfrom_llm_and_toolsù   s     ÿýþüûz'OpenAIFunctionsAgent.from_llm_and_tools)NT)N)*Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__r   r   r   r   r$   ÚtypeÚlistÚstrr1   r   r   r8   Úpropertyr:   r;   r<   Útupler   r
   Úboolr   r   r   rN   rO   rV   Úclassmethodr\   r   r   r   r   r`   r	   r   rb   r&   r&   r&   r+   r    &   sn   
ÿ  ü
ú, ý
û#û+ý
ü"ú
ør    )r!   r"   r#   r%   c                 C   s^   d|j t|jƒ vr*d|j › d�}t|ƒ‚| jdd„ |D ƒd�}tjdd„ d	�|B |B tƒ B S )
aŸ	  Create an agent that uses OpenAI function calling.

    Args:
        llm: LLM to use as the agent. Should work with OpenAI function calling,
            so either be an OpenAI model that supports that or a wrapper of
            a different model that adds in equivalent support.
        tools: Tools this agent has access to.
        prompt: The prompt to use. See Prompt section below for more.

    Returns:
        A Runnable sequence representing an agent. It takes as input all the same input
            variables as the prompt passed in does. It returns as output either an
            AgentAction or AgentFinish.

    Raises:
        ValueError: If `agent_scratchpad` is not in the prompt.

    Example:
        Creating an agent with no memory

        .. code-block:: python

            from langchain_community.chat_models import ChatOpenAI
            from langchain.agents import AgentExecutor, create_openai_functions_agent
            from langchain import hub

            prompt = hub.pull("hwchase17/openai-functions-agent")
            model = ChatOpenAI()
            tools = ...

            agent = create_openai_functions_agent(model, tools, prompt)
            agent_executor = AgentExecutor(agent=agent, tools=tools)

            agent_executor.invoke({"input": "hi"})

            # Using with chat history
            from langchain_core.messages import AIMessage, HumanMessage

            agent_executor.invoke(
                {
                    "input": "what's my name?",
                    "chat_history": [
                        HumanMessage(content="hi! my name is bob"),
                        AIMessage(content="Hello Bob! How can I assist you today?"),
                    ],
                }
            )

    Prompt:

        The agent prompt must have an `agent_scratchpad` key that is a
            ``MessagesPlaceholder``. Intermediate agent actions and tool output
            messages will be passed in here.

        Here's an example:

        .. code-block:: python

            from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

            prompt = ChatPromptTemplate.from_messages(
                [
                    ("system", "You are a helpful assistant"),
                    MessagesPlaceholder("chat_history", optional=True),
                    ("human", "{input}"),
                    MessagesPlaceholder("agent_scratchpad"),
                ]
            )

    r4   zLPrompt must have input variable `agent_scratchpad`, but wasn't found. Found z	 instead.c                 S   s   g | ]}t |ƒ‘qS r&   r   r(   r&   r&   r+   r,   s  r-   z1create_openai_functions_agent.<locals>.<listcomp>)r<   c                 S   s   t | d ƒS )Nr=   r   )Úxr&   r&   r+   Ú<lambda>v  s   ÿz/create_openai_functions_agent.<locals>.<lambda>rA   )r5   ri   Zpartial_variablesr6   Úbindr   Zassignr   )r!   r"   r#   r7   Zllm_with_toolsr&   r&   r+   r      s&    KÿÿÿÿûúùÿN)1rf   Úcollections.abcr   Útypingr   r   r   Zlangchain_core._apir   Zlangchain_core.agentsr   r   Zlangchain_core.callbacksr	   r
   Zlangchain_core.language_modelsr   Zlangchain_core.messagesr   r   Zlangchain_core.promptsr   Zlangchain_core.prompts.chatr   r   r   Zlangchain_core.prompts.messager   Zlangchain_core.runnablesr   r   Zlangchain_core.toolsr   Z%langchain_core.utils.function_callingr   Zpydanticr   Ztyping_extensionsr   Zlangchain.agentsr   Z3langchain.agents.format_scratchpad.openai_functionsr   Z0langchain.agents.output_parsers.openai_functionsr   Úobjectr\   r    r   r&   r&   r&   r+   Ú<module>   s6    {ü