
    h5                     ^   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       G d de(             Z/dedee    dedefdZ0y) 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)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fde"e#   de"ee$      de%fd       Z&e dde!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     j/var/www/html/eduruby.in/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                 n    | j                   }d|j                  vrd|j                   }t        |      | 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%   msgs      r-   validate_promptz$OpenAIFunctionsAgent.validate_promptA   sG     &*[[V%;%;;--.0  S/!    c                     dgS )z0Get input keys. Input refers to user input here.input )r+   s    r-   
input_keyszOpenAIFunctionsAgent.input_keysW   s     yr7   c                 d    | j                   D cg c]  }t        t        |             c}S c c}w )zGet functions.)r$   dictr   r*   s     r-   	functionszOpenAIFunctionsAgent.functions\   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@   r:   )r   r%   r3   r=   format_promptto_messagesr#   predict_messagesr>   r&   _parse_ai_message)r+   r?   r@   rA   rB   r2   kselected_inputsfull_inputsr%   messagespredicted_messages               r-   planzOpenAIFunctionsAgent.planb   s    * >>PQ"&++"="=
FXAXAvayL
 
 P_P?OP***9[9%%' $ 9 9..# !: ! !% 9 9# !: ! !!334EFF#
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   rD   Nr:   )r   r%   r3   r=   rE   rF   r#   apredict_messagesr>   r&   rH   )r+   r?   r@   rB   r2   rI   rJ   rK   r%   rL   rM   s              r-   aplanzOpenAIFunctionsAgent.aplan   s     & >>PQ"&++"="=
FXAXAvayL
 
 P_P?OP***9[9%%'"&(("<"<nn #= #
 

 !!334EFF

s!   $C
CCA(C!C"%Cearly_stopping_methodc                     |dk(  rt        ddid      S |dk(  r7 | j                  |fddi|}t        |t               r|S d| }t        |      d	| }t        |      )
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. generaterA   Fz,got AgentAction with no functions provided: zBearly_stopping_method should be one of `force` or `generate`, got )r	   rN   
isinstancer4   )r+   rR   r?   rB   agent_decisionr5   s         r-   return_stopped_responsez,OpenAIFunctionsAgent.return_stopped_response   s    ( !G+PQ  !J.&TYY"$ N
 .+6%%@@PQCS/!()+ 	 or7   system_messageextra_prompt_messagesc                     |xs g }|t         ur|nt        d      }|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.
        You are a helpful AI assistant.contentz{input}r2   )variable_name)rL   )_NOT_SETr   extendr   from_templater   r   )clsr[   r\   _promptssystem_message_rL   s         r-   create_promptz"OpenAIFunctionsAgent.create_prompt   s    " ).B X- 'HI 	 )8O$R*88C $2DE	
 "844r7   callback_managerc                 n    |t         ur|nt        d      }| 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#   r%   r$   ri   r:   )rb   r   rh   )	re   r#   r$   ri   r\   r[   rB   rg   r%   s	            r-   from_llm_and_toolsz'OpenAIFunctionsAgent.from_llm_and_tools   sf    . X- 'HI 	
 """7* # 
  
-	

 
 	
r7   )NT)N)*__name__
__module____qualname____doc__r   __annotations__r   r   r   r   r&   typeliststrr.   r   r   r6   propertyr;   r=   r>   tupler   r   boolr   r   r	   rN   rQ   rZ   classmethodrb   r   r   r   r   rh   r
   r   rk   r:   r7   r-   r"   r"   &   sT    
H( 489 ,49 , '"  #* DI   I4: I I  $#	'G {C'7!89'G 'G 	'G
 'G 
{K'	('GX  $G {C'7!89G G 	G
 
{K'	(GB)") !{C'7!89) 	)
 
)V  3;KO 5 / 5  (-F(GH 5 
	 5  5D 
 ;?KO2:#
#
 !#
 ##67	#

  (-F(GH#
 !/#
 #
 
#
 #
r7   r"   r#   r$   r%   r'   c                 ,   d|j                   t        |j                        z   vrd|j                    d}t        |      | 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>v  s    'I&'( r7   )r2   )	r3   rr   partial_variablesr4   bindr   r   assignr   )r#   r$   r%   r5   r,   llm_with_toolss         r-   r   r   !  s    T f&>&>!??++,I7 	 oXXPU(V1)CA)F(VXWN""	

 	 	 +
,	-	 )Ws   BN)1ro   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   langchain_core.prompts.messager   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   objectrb   r"   r   r:   r7   r-   <module>r      s    N $ ' ' * : C < 6 
 E B ) L $ " 2 8 G!@%Pw
0 w
 Qw
t\	\H\ \ 	\r7   