
    h,                        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       G d de             Zy)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                  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 rIt        j                  dd       d|vr.|d   )|j	                  dt
              }t        |d   |	      |d<   |S # t        $ r}d}t        |      |d }~w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.   )
stacklevelr   r   r   r   )numexprImportErrorwarningswarngetr   r   )clsvaluesr'   emsgr   s         \/var/www/html/eduruby.in/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{#!  	*@  c")	*s   A 	A1A,,A1c                    | j                   gS )z2Expect input key.

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

        :meta private:
        )r   r3   s    r0   output_keyszLLMMathChain.output_keys   s       r6   c                   dd l }	 t        j                  t        j                  d}t	        |j                  |j                         i |            }t        j                  dd|      S # t        $ r}d| d| d}t        |      |d }~ww xY w)	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)r4   
expressionr'   r<   outputr.   r/   s          r0   _evaluate_expressionz!LLMMathChain._evaluate_expression   s    	) $dff5J  $$& ") ! F vvj"f--  	)*:,6Gs KF F  S/q(	)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d| }t        |      | j                  |iS Ngreen)colorverbosez^```text(.*?)```   z	
Answer: )rL   yellowzAnswer: zAnswer:zunknown format from LLM: on_textrL   r@   rC   searchDOTALLgrouprG   
startswithsplitrB   r   r4   
llm_outputrun_manager
text_matchrE   rF   r   r/   s           r0   _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-j\:CS/!((r6   c                R  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d| }t        |      | j                  |iS 7 7 7 \wrI   rP   rW   s           r0   _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-j\:CS/!((! 	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_managerrQ   r   r   predict	get_childr[   r4   inputsrY   _run_managerrX   s        r0   _callzLLMMathChain._call  sz    
 #S&@&Q&Q&SVDNN34^^++DNN+",,. , 


 ''
LAAr6   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   rb   rQ   r   r   apredictrd   r]   re   s        r0   _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 r3   s    r0   _chain_typezLLMMathChain._chain_type+  s    r6   c                0    t        ||      } | dd|i|S )Nr&   r   rn   r   )r,   r   r   kwargsr   s        r0   from_llmzLLMMathChain.from_llm/  s#     V4	1Y1&11r6   )r-   dictreturnr   )rt   z	list[str])rE   r   rt   r   )rX   r   rY   r   rt   dict[str, str])rX   r   rY   r   rt   ru   )N)rf   ru   rY   z$Optional[CallbackManagerForChainRun]rt   ru   )rf   ru   rY   z)Optional[AsyncCallbackManagerForChainRun]rt   ru   )rt   r   )r   r	   r   r
   rq   r   rt   r   )__name__
__module____qualname____doc____annotations__r   r   r   r   r   r   model_configr   classmethodr1   propertyr5   r8   rG   r[   r]   rh   rk   ro   rr   rn   r6   r0   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 2r6   r   )ry   
__future__r   r>   rC   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   rn   r6   r0   <module>r      sd    I "  	    * = 5 0 ' ) 3 
	m V25 V2V2r6   