
    @h,                        S r SSKJr  SSKrSSKrSSK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  SS	KJrJr  SS
KJr  SSKJr  SSKJr  \
" SSSS9 " S S\5      5       rg)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.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                  b   \ rS rSr% SrS\S'   SrS\S'    \rS\S	'    S
r	S\S'   Sr
S\S'   \" SSS9r\" SS9\SS j5       5       r\S S j5       r\S S j5       rS!S jr      S"S jr      S#S jr S$     S%S jjr S$     S&S jjr\S'S j5       r\\4       S(S jj5       rSrg))LLMMathChain   a]  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                     SS K nSU;   aG  [        R                  " SSS9  SU;  a,  US   b&  UR	                  S[
        5      n[        US   US	9US'   U$ ! [         a  nSn[        U5      UeS nAff = f)
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.   )
stacklevelr   r   r   r   )numexprImportErrorwarningswarngetr   r   )clsvaluesr(   emsgr   s         V/var/www/html/shao/venv/lib/python3.13/site-packages/langchain/chains/llm_math/base.pyraise_deprecationLLMMathChain.raise_deprecation   s    	* F?MM  	 &(VE]-FHf5&.6%=&P{#!  	*@  c")	*s   A 
A2A--A2c                    U R                   /$ )z"Expect input key.

:meta private:
)r   selfs    r1   
input_keysLLMMathChain.input_keys   s         c                    U R                   /$ )z#Expect output key.

:meta private:
)r   r5   s    r1   output_keysLLMMathChain.output_keys   s       r9   c                   SS K n [        R                  [        R                  S.n[	        UR                  UR                  5       0 US95      n[        R                  " SSU5      $ ! [         a  nSU SU S3n[        U5      UeS nAff = f)	Nr   )pir/   )global_dict
local_dictzLLMMathChain._evaluate("z") raised error: z4. Please try again with a valid numerical expressionz^\[|\]$ )r(   mathr>   r/   r   evaluatestrip	Exception
ValueErrorresub)r6   
expressionr(   r@   outputr/   r0   s          r1   _evaluate_expression!LLMMathChain._evaluate_expression   s    	) $dff5J  $$& ") ! F vvj"f--  	)*:,6Gs KF F  S/q(	)s   A	A' '
B1BBc                   UR                  USU R                  S9  UR                  5       n[        R                  " SU[        R
                  5      nU(       a]  UR                  S5      nU R                  U5      nUR                  SU R                  S9  UR                  USU R                  S9  SU-   nOGUR                  S	5      (       a  UnO.S	U;   a  SUR                  S	5      S
   -   nOSU 3n[        U5      eU R                  U0$ Ngreen)colorverbosez^```text(.*?)```   z	
Answer: )rQ   yellowzAnswer: zAnswer:zunknown format from LLM: on_textrQ   rD   rG   searchDOTALLgrouprK   
startswithsplitrF   r   r6   
llm_outputrun_manager
text_matchrI   rJ   r   r0   s           r1   _process_llm_result 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-j\:CS/!((r9   c                \  #    UR                  USU R                  S9I S h  vN   UR                  5       n[        R                  " SU[        R
                  5      nU(       am  UR                  S5      nU R                  U5      nUR                  SU R                  S9I S h  vN   UR                  USU R                  S9I S h  vN   SU-   nOGUR                  S	5      (       a  UnO.S	U;   a  SUR                  S	5      S
   -   nOSU 3n[        U5      eU R                  U0$  GN N Nd7frN   rU   r\   s           r1   _aprocess_llm_result!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-j\:CS/!((! 	S JSs5   D,D%B D,"D(#"D,D*A D,(D,*D,c                   U=(       d    [         R                  " 5       nUR                  XR                     5        U R                  R                  XR                     S/UR                  5       S9nU R                  XC5      $ Nz	```output)r   stop	callbacks)r   get_noop_managerrV   r   r   predict	get_childr`   r6   inputsr^   _run_managerr]   s        r1   _callLLMMathChain._call  st    
 #S&@&Q&Q&SVNN34^^++NN+",,. , 


 ''
AAr9   c                J  #    U=(       d    [         R                  " 5       nUR                  XR                     5      I S h  vN   U R                  R                  XR                     S/UR                  5       S9I S h  vN nU R                  XC5      I S h  vN $  N[ N N7frf   )r   ri   rV   r   r   apredictrk   rc   rl   s        r1   _acallLLMMathChain._acall  s     
 #X&E&V&V&X""6..#9:::>>22NN+",,. 3 
 


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

 Is5   ?B#B=B#?B B#B!B#B#!B#c                    g)Nllm_math_chain r5   s    r1   _chain_typeLLMMathChain._chain_type+  s    r9   c                (    [        XS9nU " SSU0UD6$ )Nr'   r   rw   r   )r-   r   r   kwargsr   s        r1   from_llmLLMMathChain.from_llm/  s!     4	1Y1&11r9   rw   )r.   dictreturnr   )r   z	list[str])rI   r   r   r   )r]   r   r^   r   r   dict[str, str])r]   r   r^   r   r   r   )N)rm   r   r^   z$Optional[CallbackManagerForChainRun]r   r   )rm   r   r^   z)Optional[AsyncCallbackManagerForChainRun]r   r   )r   r   )r   r	   r   r
   r{   r   r   r   )__name__
__module____qualname____firstlineno____doc____annotations__r   r   r   r   r   r   model_configr   classmethodr2   propertyr7   r;   rK   r`   rc   ro   rs   rx   r|   __static_attributes__rw   r9   r1   r   r      s   sj '+C	$+*!'F'IIsJ $L
 (#  $*     ! !.,)) 0) 
	).)) 5) 
	)4 =ABB :B 
	B" BFII ?I 
	I      &,22 #2 	2
 
2 2r9   r   )r   
__future__r   rB   rG   r*   typingr   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   rw   r9   r1   <module>r      sd    I "  	    * = 5 0 ' ) 3 
	m V25 V2V2r9   