HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //usr/local/lib/python3.10/dist-packages/langchain/chains/llm_math/__pycache__/base.cpython-310.pyc
o

���g;,�@s�dZddlmZddlZddlZddlZddlmZmZm	Z	m
Z
ddlmZddl
mZmZddlmZddlmZdd	lmZmZdd
lmZddlmZddlmZed
ddd�Gdd�de��ZdS)zCChain that interprets a prompt and executes python code to do math.�)�annotationsN)�Any�Dict�List�Optional)�
deprecated)�AsyncCallbackManagerForChainRun�CallbackManagerForChainRun)�BaseLanguageModel)�BasePromptTemplate)�
ConfigDict�model_validator)�Chain��LLMChain)�PROMPTz0.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.htmlz1.0)�since�message�removalc@s�eZdZUdZded<dZded<	eZded<	d	Zd
ed<dZ	d
ed
<e
ddd�Zedd�e
d7dd���Zed8dd��Zed8dd��Zd9dd �Zd:d%d&�Zd;d(d)�Z	d<d=d,d-�Z	d<d>d/d0�Zed?d1d2��Ze
efd@d5d6��ZdS)A�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:: none

            ================================ 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_chainNzOptional[BaseLanguageModel]�llmr�prompt�question�str�	input_key�answer�
output_keyT�forbid)�arbitrary_types_allowed�extra�before)�mode�valuesr�returnrcCsnzddl}Wntytd��wd|vr5t�d�d|vr5|ddur5|�dt�}t|d|d�|d<|S)NrzXLLMMathChain requires the numexpr package. Please install it with `pip install numexpr`.rz�Directly instantiating an LLMMathChain with an llm is deprecated. Please instantiate with llm_chain argument or using the from_llm class method.rr�rr)�numexpr�ImportError�warnings�warn�getrr)�clsr#r&r�r,�I/usr/local/lib/python3.10/dist-packages/langchain/chains/llm_math/base.py�raise_deprecation�s���zLLMMathChain.raise_deprecation�	List[str]cC�|jgS)z2Expect input key.

        :meta private:
        )r��selfr,r,r-�
input_keys��zLLMMathChain.input_keyscCr0)z3Expect output key.

        :meta private:
        )rr1r,r,r-�output_keys�r4zLLMMathChain.output_keys�
expressionc
Cspddl}ztjtjd�}t|j|��i|d��}Wnty0}ztd|�d|�d���d}~wwt	�
dd|�S)	Nr)�pi�e)�global_dict�
local_dictzLLMMathChain._evaluate("z") raised error: z4. Please try again with a valid numerical expressionz^\[|\]$�)r&�mathr7r8r�evaluate�strip�	Exception�
ValueError�re�sub)r2r6r&r:�outputr8r,r,r-�_evaluate_expression�s"�����z!LLMMathChain._evaluate_expression�
llm_output�run_managerr	�Dict[str, str]cCs�|j|d|jd�|��}t�d|tj�}|r7|�d�}|�|�}|jd|jd�|j|d|jd�d|}n|�d	�r?|}nd	|vrMd|�	d	�d
}nt
d|����|j|iS�N�green)�color�verbosez^```text(.*?)```�z	
Answer: )rK�yellowzAnswer: zAnswer:���zunknown format from LLM: ��on_textrKr>rA�search�DOTALL�grouprD�
startswith�splitr@r�r2rErF�
text_matchr6rCrr,r,r-�_process_llm_result�s




z LLMMathChain._process_llm_resultrc�s��|j|d|jd�IdH|��}t�d|tj�}|rA|�d�}|�|�}|jd|jd�IdH|j|d|jd�IdHd|}n|�d	�rI|}nd	|vrWd|�	d	�d
}nt
d|����|j|iSrHrOrVr,r,r-�_aprocess_llm_result�s �




z!LLMMathChain._aprocess_llm_result�inputs�$Optional[CallbackManagerForChainRun]cCsF|pt��}|�||j�|jj||jdg|��d�}|�||�S�Nz	```output)r�stop�	callbacks)r	�get_noop_managerrPrr�predict�	get_childrX�r2rZrF�_run_managerrEr,r,r-�_calls�zLLMMathChain._call�)Optional[AsyncCallbackManagerForChainRun]c�sZ�|pt��}|�||j�IdH|jj||jdg|��d�IdH}|�||�IdHSr\)rr_rPrr�apredictrarYrbr,r,r-�_acalls��zLLMMathChain._acallcCsdS)N�llm_math_chainr,r1r,r,r-�_chain_type$szLLMMathChain._chain_typer
�kwargscKst||d�}|dd|i|��S)Nr%rr,r)r+rrrjrr,r,r-�from_llm(szLLMMathChain.from_llm)r#rr$r)r$r/)r6rr$r)rErrFr	r$rG)rErrFrr$rG)N)rZrGrFr[r$rG)rZrGrFrer$rG)r$r)rr
rrrjrr$r)�__name__�
__module__�__qualname__�__doc__�__annotations__rrrrrr�model_configr
�classmethodr.�propertyr3r5rDrXrYrdrgrirkr,r,r,r-rs@

u�


���r)ro�
__future__rr<rAr(�typingrrrr�langchain_core._apir�langchain_core.callbacksrr	�langchain_core.language_modelsr
�langchain_core.promptsr�pydanticrr
�langchain.chains.baser�langchain.chains.llmr� langchain.chains.llm_math.promptrrr,r,r,r-�<module>s(�