
    ih;,                        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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       G d de             Zy)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)PROMPTz0.2.13zThis 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)sincemessageremovalc                  L   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      Z ed      edd              Zedd       Zedd       ZddZ	 	 	 	 	 	 d dZ	 	 	 	 	 	 d!dZ	 d"	 	 	 	 	 d#dZ	 d"	 	 	 	 	 d$dZed%d       Zeef	 	 	 	 	 	 	 d&d       Zy)'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_chainNzOptional[BaseLanguageModel]llmr   promptquestionstr	input_keyanswer
output_keyTforbid)arbitrary_types_allowedextrabefore)modec                    	 dd l }d|v rGt        j                  d       d|vr.|d   )|j	                  dt
              }t        |d   |      |d<   |S # t        $ r t        d      w xY w)Nr   zXLLMMathChain requires the numexpr package. Please install it with `pip install numexpr`.r   zDirectly instantiating an LLMMathChain with an llm is deprecated. Please instantiate with llm_chain argument or using the from_llm class method.r   r   r   r   )numexprImportErrorwarningswarngetr   r   )clsvaluesr'   r   s       \/var/www/html/dev/engine/venv/lib/python3.12/site-packages/langchain/chains/llm_math/base.pyraise_deprecationzLLMMathChain.raise_deprecation   s    	 F?MM 
 &(VE]-FHf5&.6%=&P{#  	@ 	s   A A(c                    | j                   gS )z2Expect input key.

        :meta private:
        )r   selfs    r.   
input_keyszLLMMathChain.input_keys   s         c                    | j                   gS )z3Expect output key.

        :meta private:
        )r   r1   s    r.   output_keyszLLMMathChain.output_keys   s       r4   c                   dd l }	 t        j                  t        j                  d}t	        |j                  |j                         i |            }t        j                  dd|      S # t        $ r}t        d| d| d      d }~ww xY w)	Nr   )pie)global_dict
local_dictzLLMMathChain._evaluate("z") raised error: z4. Please try again with a valid numerical expressionz^\[|\]$ )r'   mathr8   r9   r   evaluatestrip	Exception
ValueErrorresub)r2   
expressionr'   r;   outputr9   s         r.   _evaluate_expressionz!LLMMathChain._evaluate_expression   s    	 $dff5J  $$& ") ! F vvj"f--  	*:,6Gs KF F 	s   AA) )	B	2BB	c                
   |j                  |d| j                         |j                         }t        j                  d|t        j
                        }|rc|j                  d      }| j                  |      }|j                  d| j                         |j                  |d| j                         d|z   }n>|j                  d	      r|}n*d	|v rd|j                  d	      d
   z   }nt        d|       | j                  |iS Ngreen)colorverbosez^```text(.*?)```   z	
Answer: )rK   yellowzAnswer: zAnswer:zunknown format from LLM: on_textrK   r?   rB   searchDOTALLgrouprF   
startswithsplitrA   r   r2   
llm_outputrun_manager
text_matchrD   rE   r   s          r.   _process_llm_resultz LLMMathChain._process_llm_result   s     	Jgt||L%%'
YY2J		J
#))!,J..z:FdllChM&(F""9-F*$*"2"29"=b"AAF8EFF((r4   c                N  K   |j                  |d| j                         d {    |j                         }t        j                  d|t        j
                        }|rs|j                  d      }| j                  |      }|j                  d| j                         d {    |j                  |d| j                         d {    d|z   }n>|j                  d	      r|}n*d	|v rd|j                  d	      d
   z   }nt        d|       | j                  |iS 7 7 ~7 ZwrH   rO   rV   s          r.   _aprocess_llm_resultz!LLMMathChain._aprocess_llm_result   s    
 !!*GT\\!RRR%%'
YY2J		J
#))!,J..z:F%%lDLL%III%%fHdll%SSS&(F""9-F*$*"2"29"=b"AAF8EFF(( 	S JSs5   "D%DA=D%"D!#%D%D#	AD%!D%#D%c                   |xs t        j                         }|j                  || j                            | j                  j                  || j                     dg|j                               }| j                  ||      S Nz	```output)r   stop	callbacks)r
   get_noop_managerrP   r   r   predict	get_childrZ   r2   inputsrX   _run_managerrW   s        r.   _callzLLMMathChain._call  sz    
 #S&@&Q&Q&SVDNN34^^++DNN+",,. , 


 ''
LAAr4   c                J  K   |xs t        j                         }|j                  || j                            d {    | j                  j                  || j                     dg|j                                d {   }| j                  ||       d {   S 7 `7  7 wr^   )r	   ra   rP   r   r   apredictrc   r\   rd   s        r.   _acallzLLMMathChain._acall  s     
 #X&E&V&V&X""6$..#9:::>>22DNN+",,. 3 
 


 ..z<HHH 	;

 Is4   :B#BAB#>B?B#B!B#B#!B#c                     y)Nllm_math_chain r1   s    r.   _chain_typezLLMMathChain._chain_type$  s    r4   c                0    t        ||      } | dd|i|S )Nr&   r   rm   r   )r,   r   r   kwargsr   s        r.   from_llmzLLMMathChain.from_llm(  s#     V4	1Y1&11r4   )r-   r   returnr   )rr   z	List[str])rD   r   rr   r   )rW   r   rX   r
   rr   Dict[str, str])rW   r   rX   r	   rr   rs   )N)re   rs   rX   z$Optional[CallbackManagerForChainRun]rr   rs   )re   rs   rX   z)Optional[AsyncCallbackManagerForChainRun]rr   rs   )rr   r   )r   r   r   r   rp   r   rr   r   )__name__
__module____qualname____doc____annotations__r   r   r   r   r   r   model_configr   classmethodr/   propertyr3   r6   rF   rZ   r\   rg   rj   rn   rq   rm   r4   r.   r   r      s   sj '+C	$+*!'F'IIsJ $L
 (#  $&     ! !.*)),F)	)()) 5) 
	)2 =ABB :B 
	B" BFII ?I 
	I      &,22 #2 	2
 
2 2r4   r   )rw   
__future__r   r=   rB   r)   typingr   r   r   r   langchain_core._apir   langchain_core.callbacksr	   r
   langchain_core.language_modelsr   langchain_core.promptsr   pydanticr   r   langchain.chains.baser   langchain.chains.llmr    langchain.chains.llm_math.promptr   r   rm   r4   r.   <module>r      sg    I "  	  , , * = 5 0 ' ) 3 
	m O25 O2O2r4   