
    @'h4                     H   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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ddd       G d de'             Z,dedee   dedefdZ-y)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)BaseMessagePromptTemplateChatPromptTemplateHumanMessagePromptTemplateMessagesPlaceholder)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)alternativeremovalc                      e Zd ZU dZeed<   ee   ed<   eed<   e	Z
ee	   ed<   dee   fdZ ed	      defd
       Zedee   fd       Zedee   fd       Z	 	 ddeeeef      dedededeeef   f
dZ	 ddeeeef      dededeeef   fdZdedeeeef      dedefdZe  e!d      dfde"e!   de"ee#      de$fd       Z%e dd e!d      fdedee   de"e&   de"ee#      de"e!   dede'fd       Z(y)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                 T    | j                   D cg c]  }|j                   c}S c c}w )zGet allowed tools.)r$   nameselfts     s/home/kushmeetdev/Regenta/Chatbot/venv/lib/python3.12/site-packages/langchain/agents/openai_functions_agent/base.pyget_allowed_toolsz&OpenAIFunctionsAgent.get_allowed_tools;   s     $

+1+++s   %after)modec                 j    | j                   }d|j                  vrt        d|j                         | S )zValidate 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)r+   r%   s     r-   validate_promptz$OpenAIFunctionsAgent.validate_prompt?   sE     &*[[V%;%;;--.0      c                     dgS )z0Get input keys. Input refers to user input here.input )r+   s    r-   
input_keyszOpenAIFunctionsAgent.input_keysT   s     yr6   c                 d    | j                   D cg c]  }t        t        |             c}S c c}w )zGet functions.)r$   dictr   r*   s     r-   	functionszOpenAIFunctionsAgent.functionsY   s(     >BZZH/23HHHs   -Nintermediate_steps	callbackswith_functionskwargsc                    t        |      }| j                  j                  D ci c]  }|dk7  s	|||    }}t        di |d|i} | j                  j                  di |}	|	j                         }
|r)| j                  j                  |
| j                  |      }n| j                  j                  |
|      }| j                  j                  |      }|S c c}w )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.
        r2   r=   r?   )r?   r9   )r   r%   r3   r<   format_promptto_messagesr#   predict_messagesr=   r&   _parse_ai_message)r+   r>   r?   r@   rA   r2   kselected_inputsfull_inputsr%   messagespredicted_messageagent_decisions                r-   planzOpenAIFunctionsAgent.plan_   s    * >>PQ"&++"="=
FXAXAvayL
 
 P_P?OP***9[9%%' $ 9 9..# !: ! !% 9 9# !: ! ++==>OP%
s
   
CCc                   K   t        |      }| j                  j                  D ci c]  }|dk7  s	|||    }}t        di |d|i} | j                  j                  di |}|j                         }	| j                  j                  |	| j                  |       d{   }
| j                  j                  |
      }|S c c}w 7 &w)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.
        r2   rC   Nr9   )r   r%   r3   r<   rD   rE   r#   apredict_messagesr=   r&   rG   )r+   r>   r?   rA   r2   rH   rI   rJ   r%   rK   rL   rM   s               r-   aplanzOpenAIFunctionsAgent.aplan   s     & >>PQ"&++"="=
FXAXAvayL
 
 P_P?OP***9[9%%'"&(("<"<) #= #
 
 ++==>OP

s!   $C

CCA(C
!C"'C
early_stopping_methodc                     |dk(  rt        ddid      S |dk(  r5 | j                  |fddi|}t        |t               r|S t        d|       t        d	|       )
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 )r	   rN   
isinstancer4   )r+   rR   r>   rA   rM   s        r-   return_stopped_responsez,OpenAIFunctionsAgent.return_stopped_response   s    ( !G+PQSU  #j0&TYY"38<BN .+6%% B>BRS  ,-/ r6   zYou are a helpful AI assistant.)contentsystem_messageextra_prompt_messagesc                     |xs g }|r|g}ng }|j                  g |t        j                  d      t        d             t	        |      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.
        z{input}r2   )variable_name)rK   )extendr   from_templater   r   )clsr[   r\   _promptsrK   s        r-   create_promptz"OpenAIFunctionsAgent.create_prompt   sg    & ).B&'HH*88C $2DE	
 "844r6   callback_managerc                 B    | j                  ||      } | d||||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.
        )r\   r[   )r#   r%   r$   rd   r9   )rc   )ra   r#   r$   rd   r\   r[   rA   r%   s           r-   from_llm_and_toolsz'OpenAIFunctionsAgent.from_llm_and_tools   sI    . """7) # 
  
-	

 
 	
r6   )NT)N))__name__
__module____qualname____doc__r   __annotations__r   r   r   r   r&   typeliststrr.   r   r   r5   propertyr:   r<   r=   tupler   r   boolr   r   r	   rN   rQ   rY   classmethodr   r   r   r   rc   r
   r   rf   r9   r6   r-   r"   r"   $   s^    
H( 489 ,49 , '"  #( DI   I4: I I  $#	( {C'7!89( ( 	(
 ( 
{K'	((Z  $ {C'7!89  	
 
{K'	(@("( !{C'7!89( 	(
 
(T  3@53
 LP 5 / 5
  (-F(GH 5 
 5  5D 
 ;?KO2?53
 
 
 ! 
 ##67	 

  (-F(GH 
 !/ 
  
 
 
  
r6   r"   r#   r$   r%   r'   c                 ,   d|j                   t        |j                        z   vrt        d|j                    d      | j	                  |D cg c]  }t        |       c}      }t        j                  d       |z  |z  t               z  }|S c c}w )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"),
                ]
            )
    r2   zLPrompt must have input variable `agent_scratchpad`, but wasn't found. Found z	 instead.)r=   c                     t        | d         S )Nr>   r   )xs    r-   <lambda>z/create_openai_functions_agent.<locals>.<lambda>l  s    'I&'( r6   )r2   )	r3   rm   partial_variablesr4   bindr   r   assignr   )r#   r$   r%   r,   llm_with_toolsagents         r-   r   r     s    P f&>&>!?? ++,I7
 	
 XXPU(V1)CA)F(VXWN""	

 	 	 +
,	- 
 L )Ws   BN).rj   collections.abcr   typingr   r   r   langchain_core._apir   langchain_core.agentsr   r	   langchain_core.callbacksr
   r   langchain_core.language_modelsr   langchain_core.messagesr   r   langchain_core.promptsr   langchain_core.prompts.chatr   r   r   r   langchain_core.runnablesr   r   langchain_core.toolsr   %langchain_core.utils.function_callingr   pydanticr   typing_extensionsr   langchain.agentsr   3langchain.agents.format_scratchpad.openai_functionsr   0langchain.agents.output_parsers.openai_functionsr   r"   r   r9   r6   r-   <module>r      s    N $ ' ' * : C < 6  C ) L $ " 2
 G!@%Pr
0 r
 Qr
jZ	Z#+H#5Z?QZZr6   