
    Ng;,                        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dS )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                  D   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d0d!Zd1d#Z	 d2d3d&Z	 d2d4d(Zed5d)            Zeefd6d,            ZdS )7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)modevaluesr   returnr   c                    	 dd l }n# t          $ r t          d          w xY wd|v rUt          j        d           d|vr=|d         5|                    dt
                    }t          |d         |          |d<   |S )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   )clsr%   r)   r   s       Z/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain/chains/llm_math/base.pyraise_deprecationzLLMMathChain.raise_deprecation   s    	NNNN 	 	 	@  	
 F??M   
 &((VE]-FHf55&.6%=&P&P&P{#s    !	List[str]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   r3   s    r/   output_keyszLLMMathChain.output_keys   s       r6   
expressionc                *   dd l }	 t          j        t          j        d}t	          |                    |                                i |                    }n(# t          $ r}t          d| d| d          d }~ww xY wt          j
        dd|          S )	Nr   )pie)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)r4   r9   r)   r>   outputr<   s         r/   _evaluate_expressionz!LLMMathChain._evaluate_expression   s    	 $df55J  $$&& ") !   FF  	 	 	F: F F F F F  	 vj"f---s   AA 
A<!A77A<
llm_outputrun_managerr
   Dict[str, str]c                &   |                     |d| j                   |                                }t          j        d|t          j                  }|ri|                    d          }|                     |          }|                     d| j                   |                     |d| j                   d|z   }nM|                    d	          r|}n5d	|v rd|	                    d	          d
         z   }nt          d|           | j        |iS Ngreen)colorverbosez^```text(.*?)```   z	
Answer: )rP   yellowzAnswer: zAnswer:zunknown format from LLM: on_textrP   rB   rE   searchDOTALLgrouprH   
startswithsplitrD   r   r4   rI   rJ   
text_matchr9   rG   r   s          r/   _process_llm_resultz LLMMathChain._process_llm_result   s'    	Jgt|LLL%%''
Y2J	JJ
 	G#))!,,J..z::FdlCCChMMM&(FF""9-- 	GFF*$$*"2"29"="=b"AAFFEEEFFF((r6   r	   c                N  K   |                     |d| j                   d {V  |                                }t          j        d|t          j                  }|ru|                    d          }|                     |          }|                     d| j                   d {V  |                     |d| j                   d {V  d|z   }nM|                    d	          r|}n5d	|v rd|	                    d	          d
         z   }nt          d|           | j        |iS rM   rT   r[   s          r/   _aprocess_llm_resultz!LLMMathChain._aprocess_llm_result   sa     
 !!*GT\!RRRRRRRRR%%''
Y2J	JJ
 	G#))!,,J..z::F%%lDL%IIIIIIIII%%fHdl%SSSSSSSSS&(FF""9-- 	GFF*$$*"2"29"="=b"AAFFEEEFFF((r6   inputs$Optional[CallbackManagerForChainRun]c                   |pt          j                    }|                    || j                            | j                            || j                 dg|                                          }|                     ||          S Nz	```output)r   stop	callbacks)r
   get_noop_managerrU   r   r   predict	get_childr]   r4   r`   rJ   _run_managerrI   s        r/   _callzLLMMathChain._call  s    
 #S&@&Q&S&SVDN3444^++DN+",,.. , 
 


 ''
LAAAr6   )Optional[AsyncCallbackManagerForChainRun]c                6  K   |pt          j                    }|                    || j                            d {V  | j                            || j                 dg|                                           d {V }|                     ||           d {V S rc   )r	   rf   rU   r   r   apredictrh   r_   ri   s        r/   _acallzLLMMathChain._acall  s      
 #X&E&V&X&X""6$.#9:::::::::>22DN+",,.. 3 
 
 
 
 
 
 
 


 ..z<HHHHHHHHHr6   c                    dS )Nllm_math_chain r3   s    r/   _chain_typezLLMMathChain._chain_type$  s    r6   r   kwargsc                8    t          ||          } | dd|i|S )Nr(   r   rr   r   )r.   r   r   rt   r   s        r/   from_llmzLLMMathChain.from_llm(  s1     V444	s11Y1&111r6   )r%   r   r&   r   )r&   r1   )r9   r   r&   r   )rI   r   rJ   r
   r&   rK   )rI   r   rJ   r	   r&   rK   )N)r`   rK   rJ   ra   r&   rK   )r`   rK   rJ   rl   r&   rK   )r&   r   )r   r   r   r   rt   r   r&   r   )__name__
__module____qualname____doc____annotations__r   r   r   r   r   r   model_configr   classmethodr0   propertyr5   r8   rH   r]   r_   rk   ro   rs   rv   rr   r6   r/   r   r      s        s sj '+C++++*!'F''''IIJ: $  L
 _(###   [ $#&       X  ! ! ! X!. . . .*) ) ) )() ) ) )2 =AB B B B B" BFI I I I I       X   &,2 2 2 2 [2 2 2r6   r   )rz   
__future__r   r@   rE   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   rr   r6   r/   <module>r      sv   I I " " " " " "  				  , , , , , , , , , , , , * * * * * *        = < < < < < 5 5 5 5 5 5 0 0 0 0 0 0 0 0 ' ' ' ' ' ' ) ) ) ) ) ) 3 3 3 3 3 3 
	m   O2 O2 O2 O2 O25 O2 O2 O2 O2 O2r6   