
    @h5                     Z   S r SSKJr  SSKJrJrJr  SSKJr  SSK	J
r
Jr  SSKJrJr  SSKJr  SSKJrJr  SS	KJr  SS
KJrJrJr  SSKJr  SSKJrJr  SSKJ r   SSK!J"r"  SSK#J$r$  SSK%J&r&  SSK'J(r(  SSK)J*r*  SSK+J,r,  \-" 5       r.\" SSSS9 " S S\(5      5       r/S\S\\    S\S\4S jr0g) 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                      \ rS rSr% Sr\\S'   \\   \S'   \	\S'   \
r\\
   \S'   S\\   4S jr\" S	S
9S\4S j5       r\S\\   4S j5       r\S\\   4S j5       r  SS\\\\4      S\S\S\S\\\4   4
S jjr SS\\\\4      S\S\S\\\4   4S jjrS\S\\\\4      S\S\4S jr \!\"S4S\#\$   S\#\\%      S\&4S jj5       r'\!SS\"4S\S\\   S\#\(   S\#\\%      S\#\$   S\S\)4S jj5       r*Sr+g)OpenAIFunctionsAgent&   aN  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                 V    U R                    Vs/ sH  oR                  PM     sn$ s  snf )zGet allowed tools.)r%   nameselfts     d/var/www/html/shao/venv/lib/python3.13/site-packages/langchain/agents/openai_functions_agent/base.pyget_allowed_tools&OpenAIFunctionsAgent.get_allowed_tools=   s      $

+
1
+++s   &after)modec                 r    U R                   nSUR                  ;  a  SUR                   3n[        U5      eU $ )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_prompt$OpenAIFunctionsAgent.validate_promptA   sG     &*[[V%;%;;--.0  S/!    c                     S/$ )z0Get input keys. Input refers to user input here.input )r,   s    r.   
input_keysOpenAIFunctionsAgent.input_keysW   s     yr:   c                 h    U R                    Vs/ sH  n[        [        U5      5      PM     sn$ s  snf )zGet functions.)r%   dictr   r+   s     r.   	functionsOpenAIFunctionsAgent.functions\   s,     >BZZHZ/23ZHHHs   /Nintermediate_steps	callbackswith_functionskwargsc                    [        U5      nU R                  R                   Vs0 sH  ofS:w  d  M
  XdU   _M     nn[        S0 UDSU0D6nU R                  R                  " S0 UD6n	U	R                  5       n
U(       a&  U R                  R                  U
U R                  US9nOU R                  R                  U
US9nU R                  R                  U5      $ s  snf )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.
r4   rB   rE   )rE   r=   )r   r&   r5   rA   format_promptto_messagesr$   predict_messagesrB   r'   _parse_ai_message)r,   rD   rE   rF   rG   r4   kselected_inputsfull_inputsr&   messagespredicted_messages               r.   planOpenAIFunctionsAgent.planb   s    * >>PQ"&++"="=
"=QFXAXLAayL"= 	 
 P_P?OP**9[9%%' $ 9 9..# !: ! !% 9 9# !: ! !!334EFF#
s
   C	Cc                   #    [        U5      nU R                  R                   Vs0 sH  oUS:w  d  M
  XSU   _M     nn[        S0 UDSU0D6nU R                  R                  " S0 UD6nUR                  5       n	U R                  R                  U	U R                  US9I Sh  vN n
U R                  R                  U
5      $ s  snf  N$7f)ax  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.
r4   rI   Nr=   )r   r&   r5   rA   rJ   rK   r$   apredict_messagesrB   r'   rM   )r,   rD   rE   rG   r4   rN   rO   rP   r&   rQ   rR   s              r.   aplanOpenAIFunctionsAgent.aplan   s     & >>PQ"&++"="=
"=QFXAXLAayL"= 	 
 P_P?OP**9[9%%'"&(("<"<nn #= #
 

 !!334EFF

s!   $CC 	C A%C C!%Cearly_stopping_methodc                     US:X  a  [        SS0S5      $ US:X  a<  U R                  " U4SS0UD6n[        U[         5      (       a  U$ SU 3n[        U5      eS	U 3n[        U5      e)
av  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. generaterF   Fz,got AgentAction with no functions provided: zBearly_stopping_method should be one of `force` or `generate`, got )r	   rS   
isinstancer6   )r,   rY   rD   rG   agent_decisionr7   s         r.   return_stopped_response,OpenAIFunctionsAgent.return_stopped_response   s    ( !G+PQ  !J.!YY"$ N
 .+66%%@@PQCS/!()+ 	 or:   system_messageextra_prompt_messagesc                     U=(       d    / nU[         La  UO[        SS9nU(       a  U/O/ nUR                  / UQ[        R                  " S5      P[        SS9P5        [        US9$ )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   )variable_name)rQ   )_NOT_SETr   extendr   from_templater   r   )clsrc   rd   _promptssystem_message_rQ   s         r.   create_prompt"OpenAIFunctionsAgent.create_prompt   s    " ).B X- 'HI 	 )8O$R*88C $2DE	
 "844r:   callback_managerc                 d    U[         La  UO[        SS9nU R                  UUS9nU " SUUUUS.UD6$ )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.
rf   rg   )rd   rc   )r$   r&   r%   rr   r=   )rj   r   rp   )	rm   r$   r%   rr   rd   rc   rG   ro   r&   s	            r.   from_llm_and_tools'OpenAIFunctionsAgent.from_llm_and_tools   sf    . X- 'HI 	
 """7* # 
  
-	

 
 	
r:   r=   )NT)N),__name__
__module____qualname____firstlineno____doc__r   __annotations__r   r   r   r   r'   typeliststrr/   r   r   r8   propertyr>   rA   rB   tupler   r   boolr   r   r	   rS   rW   ra   classmethodrj   r   r   r   r   rp   r
   r   rt   __static_attributes__r=   r:   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#
 !/#
 #
 
#
 #
r:   r"   r$   r%   r&   r(   c                 *   SUR                   [        UR                  5      -   ;  a  SUR                    S3n[        U5      eU R	                  U Vs/ sH  n[        U5      PM     snS9n[        R                  " S S9U-  U-  [        5       -  $ s  snf )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.)rB   c                     [        U S   5      $ )NrD   r   )xs    r.   <lambda>/create_openai_functions_agent.<locals>.<lambda>v  s    'I&'(r:   )r4   )	r5   r}   partial_variablesr6   bindr   r   assignr   )r$   r%   r&   r7   r-   llm_with_toolss         r.   r   r   !  s    T f&>&>!??++,I7 	 oXXPU(VPU1)CA)FPU(VXWN""	

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