
    3fi4                     V   d Z ddlmZ ddl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Z.y) zHModule implements an agent that uses OpenAI's APIs function enabled API.    )Sequence)Any)
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z  f
dZ	 ddeeeef      dededeez  fdZdedeeeef      dedefdZee dfde!dz  dee"   dz  de#fd       Z$edde fdedee   de%dz  dee"   dz  de!dz  dede&fd       Z'y)OpenAIFunctionsAgentaD  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`.
    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     r/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_classic/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_prompt@   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_keysV   s     yr5   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.
            with_functions: Whether to use functions.
            **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`.
        r0   r<   r>   )r>   r8   )r   r#   r1   r;   format_promptto_messagesr!   invoker<   r$   parse_ai_message)r)   r=   r>   r?   r@   r0   kselected_inputsfull_inputsr#   messagespredicted_messages               r+   planzOpenAIFunctionsAgent.plan`   s    * >>PQ"&++"="=
FXAXAvayL
 
 P_P?OP***9[9%%' $..# !0 ! !%# !0 ! !!223DEE#
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.
            **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.
        r0   rB   Nr8   )r   r#   r1   r;   rC   rD   r!   ainvoker<   r$   rF   )r)   r=   r>   r@   r0   rG   rH   rI   r#   rJ   rK   s              r+   aplanzOpenAIFunctionsAgent.aplan   s     & >>PQ"&++"="=
FXAXAvayL
 
 P_P?OP***9[9%%'"&(("2"2nn #3 #
 

 !!223DEE

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. generater?   Fz,got AgentAction with no functions provided: zBearly_stopping_method should be one of `force` or `generate`, got )r   rL   
isinstancer2   )r)   rP   r=   r@   agent_decisionr3   s         r+   return_stopped_responsez,OpenAIFunctionsAgent.return_stopped_response   s    ( !G+PQ  !J.&TYY"$ N
 .+6%%@@PQCS/!()+ 	 or5   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}r0   )variable_name)rJ   )_NOT_SETr   extendr   from_templater   r   )clsrY   rZ   _promptssystem_message_rJ   s         r+   create_promptz"OpenAIFunctionsAgent.create_prompt   s    " ).B X- 'HI 	 )8O$R*88C $2DE	
 "844r5   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.
            extra_prompt_messages: Extra prompt messages to use.
            system_message: The system message to use.
                Defaults to a default system message.
            kwargs: Additional parameters to pass to the agent.
        r\   r]   )rZ   rY   )r!   r#   r"   rg   r8   )r`   r   rf   )	rc   r!   r"   rg   rZ   rY   r@   re   r#   s	            r+   from_llm_and_toolsz'OpenAIFunctionsAgent.from_llm_and_tools   sf    . X- 'HI 	
 """7* # 
  
-	

 
 	
r5   )NT)N)(__name__
__module____qualname____doc__r
   __annotations__r   r   r   r   r$   typeliststrr,   r   r   r4   propertyr9   r;   r<   tupler   r	   boolr   r   rL   rO   rX   classmethodr`   r   r   r   rf   r   r   ri   r8   r5   r+   r    r    &   sI    
H( 489 ,49 , '"  #* DI   I4: I I  $#	'F {C'7!89'F 'F 	'F
 'F 
{	"'FX  $F {C'7!89F F 	F
 
{	"FB)") !{C'7!89) 	)
 
)V  08HL 5%, 5  $$=>E 5 
	 5  5D 
 8<HL/7#
#
 !#
 .4	#

  $$=>E#
 &,#
 #
 
#
 #
r5   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 )aJ	  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

        ```python
        from langchain_openai import ChatOpenAI
        from langchain_classic.agents import (
            AgentExecutor,
            create_openai_functions_agent,
        )
        from langchain_classic 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:

        ```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"),
            ]
        )
        ```
    r0   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>w  s    'I&'( r5   )r0   )	r1   rp   partial_variablesr2   bindr   r   assignr   )r!   r"   r#   r3   r*   llm_with_toolss         r+   r   r     s    Z f&>&>!??++,I7 	 oXXPU(V1)CA)F(VXWN""	

 	 	 +
,	-	 )Ws   BN)/rm   collections.abcr   typingr   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_classic.agentsr   ;langchain_classic.agents.format_scratchpad.openai_functionsr   8langchain_classic.agents.output_parsers.openai_functionsr   objectr`   r    r   r8   r5   r+   <module>r      s    N $  * : C < 6 
 E B ) L $ " : 8 G!@%Pu
0 u
 Qu
p_	_H_ _ 	_r5   