
    3fi,                        d Z ddlmZ ddlZddlZddl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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)
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:

        ```bash
        pip install -U langgraph
        ```

        ```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
                    )
                )

            model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
            tools = [calculator]
            model_with_tools = model.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 model_with_tools.ainvoke(state["messages"], config)
                return {"messages": [response]}

            async def acall_model(state: ChainState, config: RunnableConfig):
                response = await model.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()

        ```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()
        ```

        ```txt
        ================================ 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:
        ```python
        from langchain_classic.chains import LLMMathChain
        from langchain_openai import OpenAI

        llm_math = LLMMathChain.from_llm(OpenAI())
        ```
    r   	llm_chainNzBaseLanguageModel | None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         d/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_classic/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 )zExpect input key.)r   selfs    r/   
input_keyszLLMMathChain.input_keys   s         c                    | j                   gS )zExpect output key.)r   r2   s    r/   output_keyszLLMMathChain.output_keys   s       r5   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&   mathr9   r-   r   evaluatestrip	Exception
ValueErrorresub)r3   
expressionr&   r;   outputr-   r.   s          r/   _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: )rK   yellowzAnswer: zAnswer:zunknown format from LLM: on_textrK   r?   rB   searchDOTALLgrouprF   
startswithsplitrA   r   r3   
llm_outputrun_manager
text_matchrD   rE   r   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-j\:CS/!((r5   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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-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_managerrP   r   r   predict	get_childrZ   r3   inputsrX   _run_managerrW   s        r/   _callzLLMMathChain._call  sz    
 #S&@&Q&Q&SVDNN34^^++DNN+",,. , 


 ''
LAAr5   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 r2   s    r/   _chain_typezLLMMathChain._chain_type(  s    r5   c                0    t        ||      } | dd|i|S )zCreate a LLMMathChain from a language model.

        Args:
            llm: a language model
            prompt: a prompt template
            **kwargs: additional arguments
        r%   r   rm   r   )r+   r   r   kwargsr   s        r/   from_llmzLLMMathChain.from_llm,  s#     V4	1Y1&11r5   )r,   dictreturnr   )rs   z	list[str])rD   r   rs   r   )rW   r   rX   r   rs   dict[str, str])rW   r   rX   r   rs   rt   )N)re   rt   rX   z!CallbackManagerForChainRun | Noners   rt   )re   rt   rX   z&AsyncCallbackManagerForChainRun | Noners   rt   )rs   r   )r   r   r   r	   rp   r   rs   r   )__name__
__module____qualname____doc____annotations__r   r   r   r   r   r
   model_configr   classmethodr0   propertyr4   r7   rF   rZ   r\   rg   rj   rn   rq   rm   r5   r/   r   r      s   vp $(C	!(*!'F'IIsJ $L
 (#  $*     ! !.,)) 0) 
	).)) 5) 
	)4 :>BB 7B 
	B" ?CII <I 
	I      &,22 #2 	2
 
2 2r5   r   )rx   
__future__r   r=   rB   r(   typingr   langchain_core._apir   langchain_core.callbacksr   r   langchain_core.language_modelsr   langchain_core.promptsr	   pydanticr
   r   langchain_classic.chains.baser   langchain_classic.chains.llmr   (langchain_classic.chains.llm_math.promptr   r   rm   r5   r/   <module>r      sd    I "  	   * = 5 0 / 1 ; 
	m Z25 Z2Z2r5   