Ë
    ´Œj»5  ã                   ó^  — 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     úv/var/www/html/Fitness-lenito-AI-main/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 )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)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¿ZºZÓH¹Z¸”Ô/°Ó2Õ3¸ZÑ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Ðà"&§+¡+×"=Ò"=ó
Ù"=˜QÀÐFXÓAXˆAˆv�a‰y‰LÐ"=ð 	ð 
ô ÑP˜_ÑPÐ?OÒPˆØ*�—‘×*Ñ*Ñ9¨[Ñ9ˆØ×%Ñ%Ó'ˆÙØ $§¡× 9Ñ 9ØØŸ.™.Ø#ð !:ó !Ñð !%§¡× 9Ñ 9ØØ#ð !:ó !Ðð ×!Ñ!×3Ñ3Ð4EÓ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Ðà"&§+¡+×"=Ò"=ó
Ù"=˜QÀÐFXÓAXˆAˆv�a‰y‰LÐ"=ð 	ð 
ô ÑP˜_ÑPÐ?OÒPˆØ*�—‘×*Ñ*Ñ9¨[Ñ9ˆØ×%Ñ%Ó'ˆØ"&§(¡(×"<Ñ"<ØØ—n‘nØð #=ó #
÷ 
Ðð
 ×!Ñ!×3Ñ3Ð4EÓ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Ò.à&˜TŸY™YØ"ñà$ðð ñˆNô
 ˜.¬+Ô6Ø%Ð%Ø@ÀÐ@PÐQˆCÜ˜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ð 	ñ )8�OÑ$¸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ó ð 5ðD ð
 ;?ØKOØ2:ñ#
àð#
ð ˜Ñ!ð#
ð #Ð#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ÐØ—X‘XÑPUÓ(VÑPUÈ1Ô)CÀAÕ)FÐPUÑ(V�XÓW€Nä×"Ñ"ñô	
ð
 ñ	ð ñ	ô +Ó
,ñ	-ð	ùò )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   