a
    •˜ëj�-  ã                   @  sÂ   d Z ddlmZ ddlZddlZddl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 dd	lmZmZ dd
lmZ ddlmZ ddlmZ e
dddd�G dd„ deƒƒZdS )zCChain that interprets a prompt and executes python code to do math.é    )ÚannotationsN)ÚAnyÚOptional)Ú
deprecated)ÚAsyncCallbackManagerForChainRunÚCallbackManagerForChainRun)ÚBaseLanguageModel)ÚBasePromptTemplate)Ú
ConfigDictÚmodel_validator)ÚChain©ÚLLMChain)ÚPROMPTz0.2.13zÄThis class is deprecated and will be removed in langchain 1.0. See API reference for replacement: https://api.python.langchain.com/en/latest/chains/langchain.chains.llm_math.base.LLMMathChain.htmlz1.0)ZsinceÚmessageZremovalc                   @  s"  e Zd ZU dZded< dZded< eZded< d	Zd
ed< dZ	d
ed< e
ddd�Zedd�edddœdd„ƒƒZeddœdd„ƒZeddœdd„ƒZd
d
dœdd „Zd
d!d"d#œd$d%„Zd
d&d"d#œd'd(„Zd6d"d)d"d*œd+d,„Zd7d"d-d"d*œd.d/„Zed
dœd0d1„ƒZeefd2ddd d3œd4d5„ƒZdS )8ÚLLMMathChainaÄ  Chain that interprets a prompt and executes python code to do math.

    .. note::
        This class is deprecated. See below for a replacement implementation using
        LangGraph. The benefits of this implementation are:

        - Uses LLM tool calling features;
        - Support for both token-by-token and step-by-step streaming;
        - Support for checkpointing and memory of chat history;
        - Easier to modify or extend
          (e.g., with additional tools, structured responses, etc.)

        Install LangGraph with:

        .. code-block:: bash

            pip install -U langgraph

        .. code-block:: python

            import math
            from typing import Annotated, Sequence

            from langchain_core.messages import BaseMessage
            from langchain_core.runnables import RunnableConfig
            from langchain_core.tools import tool
            from langchain_openai import ChatOpenAI
            from langgraph.graph import END, StateGraph
            from langgraph.graph.message import add_messages
            from langgraph.prebuilt.tool_node import ToolNode
            import numexpr
            from typing_extensions import TypedDict

            @tool
            def calculator(expression: str) -> str:
                """Calculate expression using Python's numexpr library.

                Expression should be a single line mathematical expression
                that solves the problem.

    Examples:
                    "37593 * 67" for "37593 times 67"
                    "37593**(1/5)" for "37593^(1/5)"
                """
                local_dict = {"pi": math.pi, "e": math.e}
                return str(
                    numexpr.evaluate(
                        expression.strip(),
                        global_dict={},  # restrict access to globals
                        local_dict=local_dict,  # add common mathematical functions
                    )
                )

            llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
            tools = [calculator]
            llm_with_tools = llm.bind_tools(tools, tool_choice="any")

            class ChainState(TypedDict):
                """LangGraph state."""

                messages: Annotated[Sequence[BaseMessage], add_messages]

            async def acall_chain(state: ChainState, config: RunnableConfig):
                last_message = state["messages"][-1]
                response = await llm_with_tools.ainvoke(state["messages"], config)
                return {"messages": [response]}

            async def acall_model(state: ChainState, config: RunnableConfig):
                response = await llm.ainvoke(state["messages"], config)
                return {"messages": [response]}

            graph_builder = StateGraph(ChainState)
            graph_builder.add_node("call_tool", acall_chain)
            graph_builder.add_node("execute_tool", ToolNode(tools))
            graph_builder.add_node("call_model", acall_model)
            graph_builder.set_entry_point("call_tool")
            graph_builder.add_edge("call_tool", "execute_tool")
            graph_builder.add_edge("execute_tool", "call_model")
            graph_builder.add_edge("call_model", END)
            chain = graph_builder.compile()

        .. code-block:: python

            example_query = "What is 551368 divided by 82"

            events = chain.astream(
                {"messages": [("user", example_query)]},
                stream_mode="values",
            )
            async for event in events:
                event["messages"][-1].pretty_print()

        .. code-block::

            ================================ Human Message =================================

            What is 551368 divided by 82
            ================================== Ai Message ==================================
            Tool Calls:
            calculator (call_MEiGXuJjJ7wGU4aOT86QuGJS)
            Call ID: call_MEiGXuJjJ7wGU4aOT86QuGJS
            Args:
                expression: 551368 / 82
            ================================= Tool Message =================================
            Name: calculator

            6724.0
            ================================== Ai Message ==================================

            551368 divided by 82 equals 6724.

    Example:
        .. code-block:: python

            from langchain.chains import LLMMathChain
            from langchain_community.llms import OpenAI

            llm_math = LLMMathChain.from_llm(OpenAI())

    r   Ú	llm_chainNzOptional[BaseLanguageModel]Úllmr	   ÚpromptÚquestionÚstrÚ	input_keyÚanswerÚ
output_keyTZforbid)Zarbitrary_types_allowedÚextraÚbefore)ÚmodeÚdictr   )ÚvaluesÚreturnc              
   C  sŽ   zdd l }W n2 ty> } zd}t|ƒ|‚W Y d }~n
d }~0 0 d|v rŠtjddd� d|vrŠ|d d urŠ| dt¡}t|d |d	�|d< |S )
Nr   zXLLMMathChain requires the numexpr package. Please install it with `pip install numexpr`.r   z�Directly instantiating an LLMMathChain with an llm is deprecated. Please instantiate with llm_chain argument or using the from_llm class method.é   )Ú
stacklevelr   r   ©r   r   )ÚnumexprÚImportErrorÚwarningsÚwarnÚgetr   r   )Úclsr   r#   ÚeÚmsgr   © r+   ú]/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain/chains/llm_math/base.pyÚ_raise_deprecation¨   s    ÿ üzLLMMathChain._raise_deprecationz	list[str])r   c                 C  s   | j gS )z2Expect input key.

        :meta private:
        )r   ©Úselfr+   r+   r,   Ú
input_keys¿   s    zLLMMathChain.input_keysc                 C  s   | j gS )z3Expect output key.

        :meta private:
        )r   r.   r+   r+   r,   Úoutput_keysÇ   s    zLLMMathChain.output_keys)Ú
expressionr   c              
   C  s‚   dd l }z*tjtjdœ}t|j| ¡ i |d�ƒ}W n@ tyr } z(d|› d|› d�}t|ƒ|‚W Y d }~n
d }~0 0 t	 
dd|¡S )	Nr   )Úpir)   )Zglobal_dictÚ
local_dictzLLMMathChain._evaluate("z") raised error: z4. Please try again with a valid numerical expressionz^\[|\]$Ú )r#   Úmathr3   r)   r   ÚevaluateÚstripÚ	ExceptionÚ
ValueErrorÚreÚsub)r/   r2   r#   r4   Úoutputr)   r*   r+   r+   r,   Ú_evaluate_expressionÏ   s    ýÿÿ z!LLMMathChain._evaluate_expressionr   zdict[str, str])Ú
llm_outputÚrun_managerr   c                 C  s¶   |j |d| jd� | ¡ }t d|tj¡}|rn| d¡}|  |¡}|j d| jd� |j |d| jd� d| }n>| d	¡r~|}n.d	|v ršd| 	d	¡d
  }nd|› �}t
|ƒ‚| j|iS ©NZgreen)ÚcolorÚverbosez^```text(.*?)```é   z	
Answer: )rC   ZyellowzAnswer: zAnswer:éÿÿÿÿzunknown format from LLM: ©Úon_textrC   r8   r;   ÚsearchÚDOTALLÚgroupr>   Ú
startswithÚsplitr:   r   ©r/   r?   r@   Z
text_matchr2   r=   r   r*   r+   r+   r,   Ú_process_llm_resultå   s     




z LLMMathChain._process_llm_resultr   c                 Ã  sÈ   |j |d| jd�I d H  | ¡ }t d|tj¡}|r€| d¡}|  |¡}|j d| jd�I d H  |j |d| jd�I d H  d| }n>| d	¡r�|}n.d	|v r¬d| 	d	¡d
  }nd|› �}t
|ƒ‚| j|iS rA   rF   rM   r+   r+   r,   Ú_aprocess_llm_resultü   s     




z!LLMMathChain._aprocess_llm_resultz$Optional[CallbackManagerForChainRun])Úinputsr@   r   c                 C  sF   |p
t  ¡ }| || j ¡ | jj|| j dg| ¡ d�}|  ||¡S ©Nz	```output)r   ÚstopÚ	callbacks)r   Úget_noop_managerrG   r   r   ZpredictÚ	get_childrN   ©r/   rP   r@   Z_run_managerr?   r+   r+   r,   Ú_call  s    ýzLLMMathChain._callz)Optional[AsyncCallbackManagerForChainRun]c                 Ã  sX   |p
t  ¡ }| || j ¡I d H  | jj|| j dg| ¡ d�I d H }|  ||¡I d H S rQ   )r   rT   rG   r   r   ZapredictrU   rO   rV   r+   r+   r,   Ú_acall!  s    ýzLLMMathChain._acallc                 C  s   dS )NZllm_math_chainr+   r.   r+   r+   r,   Ú_chain_type/  s    zLLMMathChain._chain_typer   )r   r   Úkwargsr   c                 K  s   t ||d�}| f d|i|¤ŽS )z·Create a LLMMathChain from a language model.

        Args:
            llm: a language model
            prompt: a prompt template
            **kwargs: additional arguments
        r"   r   r   )r(   r   r   rZ   r   r+   r+   r,   Úfrom_llm3  s    zLLMMathChain.from_llm)N)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   r   r   r   r
   Zmodel_configr   Úclassmethodr-   Úpropertyr0   r1   r>   rN   rO   rW   rX   rY   r[   r+   r+   r+   r,   r      s:   

yþ ý ýýr   )r_   Ú
__future__r   r6   r;   r%   Útypingr   r   Zlangchain_core._apir   Zlangchain_core.callbacksr   r   Zlangchain_core.language_modelsr   Zlangchain_core.promptsr	   Zpydanticr
   r   Zlangchain.chains.baser   Zlangchain.chains.llmr   Z langchain.chains.llm_math.promptr   r   r+   r+   r+   r,   Ú<module>   s&   ù	