a
    dg^&                     @  s   d Z ddlm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 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 G dd deZdS )zLChain that interprets a prompt and executes python code to do symbolic math.    )annotationsN)AnyDictListOptional)BaseLanguageModel)ChainLLMChain)AsyncCallbackManagerForChainRunCallbackManagerForChainRun)BasePromptTemplate)
ConfigDict)PROMPTc                      s  e Zd ZU dZded< dZded< dZded< ed	d
dZded< ddd fddZ	e
ddddZe
ddddZdddddZdddddd Zdd!ddd"d#Zd3dd%dd&d'd(Zd4dd)dd&d*d+Ze
ddd,d-Zeefd.d/dd d0d1d2Z  ZS )5LLMSymbolicMathChaina  Chain that interprets a prompt and executes python code to do symbolic math.

    It is based on the sympy library and can be used to evaluate
    mathematical expressions.
    See https://www.sympy.org/ for more information.

    Example:
        .. code-block:: python

            from langchain.chains import LLMSymbolicMathChain
            from langchain_community.llms import OpenAI
            llm_symbolic_math = LLMSymbolicMathChain.from_llm(OpenAI())
    r
   	llm_chainquestionstr	input_keyanswer
output_keyTZforbid)Zarbitrary_types_allowedextraboolallow_dangerous_requestsr   None)kwargsreturnc                   s&   d|vrt dt jf i | d S )Nr   a  LLMSymbolicMathChain requires allow_dangerous_requests to be set. We recommend that you set `allow_dangerous_requests=False` to allow only pre-defined symbolic operations. If the some symbolic expressions are failing to evaluate, you can open a PR to add them to extend the list of allowed operations. Alternatively, you can set `allow_dangerous_requests=True` to allow any kind of input but this is STRONGLY DISCOURAGED unless you fully trust the input (and believe that the LLM itself cannot behave in a malicious way).You should absolutely NOT be deploying this in a production environment with allow_dangerous_requests=True. As this would allow a malicious actor to execute arbitrary code on your system.)
ValueErrorsuper__init__)selfr   	__class__ {/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_experimental/llm_symbolic_math/base.pyr   @   s
    zLLMSymbolicMathChain.__init__z	List[str])r   c                 C  s   | j gS )z2Expect input key.

        :meta private:
        )r   r    r#   r#   r$   
input_keysS   s    zLLMSymbolicMathChain.input_keysc                 C  s   | j gS )z3Expect output key.

        :meta private:
        )r   r%   r#   r#   r$   output_keys[   s    z LLMSymbolicMathChain.output_keys)
expressionr   c              "     sP  zdd l  W n. ty: } ztd|W Y d }~n
d }~0 0 z| jrXt j|dd}n j j j j j	 j
 j j j j j j j j j j j j fdd j fdd j j j j j j j j j j  j! j"d!}t j#||dd	}W n< t$y@ } z"t%d
| d| dW Y d }~n
d }~0 0 t&'dd|S )Nr   zCUnable to import sympy, please install it with `pip install sympy`.T)evaluatec                   s     | dS )N
   )logxsympyr#   r$   <lambda>       z;LLMSymbolicMathChain._evaluate_expression.<locals>.<lambda>c                   s     |  ddS )N      )PowRationalr,   r.   r#   r$   r0      r1   )!sincostancotseccscasinacosatansinhcoshtanhasinhacoshatanhexpr+   lnlog10sqrtZcbrt	factorialbinomialgcdlcmabssignmodpieIooNaN)Z
local_dictr)   z LLMSymbolicMathChain._evaluate("z") raised error: z4. Please try again with a valid numerical expressionz^\[|\]$ )(r/   ImportErrorr   r   Zsympifyr6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   r+   rH   rI   rJ   rK   rL   ZAbsrN   ModrP   ErR   rS   nanZ
parse_expr	Exceptionr   resub)r    r(   rQ   outputZallowed_symbolsr#   r.   r$   _evaluate_expressionc   sn    

+z)LLMSymbolicMathChain._evaluate_expressionr   zDict[str, str])
llm_outputrun_managerr   c                 C  s   |j |d| jd | }td|tj}|rn|d}| |}|j d| jd |j |d| jd d| }n:|d	r~|}n*d	|v rd|	d	d
  }nt
d| | j|iS Ngreen)colorverbosez^```text(.*?)```r2   z	
Answer: )rd   yellowzAnswer: zAnswer:zunknown format from LLM: on_textrd   stripr[   searchDOTALLgroupr^   
startswithsplitr   r   r    r_   r`   Z
text_matchr(   r]   r   r#   r#   r$   _process_llm_result   s    



z(LLMSymbolicMathChain._process_llm_resultr   c                   s   |j |d| jdI d H  | }td|tj}|r|d}| |}|j d| jdI d H  |j |d| jdI d H  d| }n:|d	r|}n*d	|v rd|	d	d
  }nt
d| | j|iS ra   rg   ro   r#   r#   r$   _aprocess_llm_result   s    



z)LLMSymbolicMathChain._aprocess_llm_resultNz$Optional[CallbackManagerForChainRun])inputsr`   r   c                 C  sF   |p
t  }||| j  | jj|| j dg| d}| ||S Nz	```output)r   stop	callbacks)r   get_noop_managerrh   r   r   Zpredict	get_childrp   r    rr   r`   Z_run_managerr_   r#   r#   r$   _call   s    zLLMSymbolicMathChain._callz)Optional[AsyncCallbackManagerForChainRun]c                   sX   |p
t  }||| j I d H  | jj|| j dg| dI d H }| ||I d H S rs   )r   rv   rh   r   r   Zapredictrw   rq   rx   r#   r#   r$   _acall   s    zLLMSymbolicMathChain._acallc                 C  s   dS )NZllm_symbolic_math_chainr#   r%   r#   r#   r$   _chain_type   s    z LLMSymbolicMathChain._chain_typer   r   )llmpromptr   r   c                 K  s   t ||d}| f d|i|S )N)r|   r}   r   r	   )clsr|   r}   r   r   r#   r#   r$   from_llm   s    zLLMSymbolicMathChain.from_llm)N)N)__name__
__module____qualname____doc____annotations__r   r   r   Zmodel_configr   propertyr&   r'   r^   rp   rq   ry   rz   r{   classmethodr   r   __classcell__r#   r#   r!   r$   r      s4   
E  r   )r   
__future__r   r[   typingr   r   r   r   Zlangchain.base_languager   Zlangchain.chains.baser   Zlangchain.chains.llmr
   Z langchain_core.callbacks.managerr   r   Zlangchain_core.prompts.baser   Zpydanticr   Z/langchain_experimental.llm_symbolic_math.promptr   r   r#   r#   r#   r$   <module>   s   