
    Ng4                         d dl Z d dlmZ d dlmZmZmZmZmZm	Z	m
Z
 d dlZd dlmZmZ d dlmZ d dlmZmZmZmZmZ d dlmZmZmZ d dlmZ d d	lmZ d d
lmZ  G d de          Z  G d de          Z!dS )    N)
HTTPStatus)AnyAsyncIteratorDictIteratorListOptionalUnion)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)BaseChatModel)	AIMessageAIMessageChunkBaseMessageHumanMessageSystemMessage)ChatGenerationChatGenerationChunk
ChatResult)Field)Response)	HTTPErrorc                   *    e Zd ZdeddfdZdefdZdS )MaritalkHTTPErrorrequest_objreturnNc                     || _         	 |                                }d|v r	|d         }nd|v r	|d         }n|}n# t          $ r
 |j        }Y nw xY w|| _        |j        | _        d S )Ndetailmessage)r   json	Exceptiontextr   status_code)selfr   response_jsonapi_messages       d/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chat_models/maritalk.py__init__zMaritalkHTTPError.__init__   s    &		+',,..M=((+H5m+++I6+ 	+ 	+ 	+%*KKK	+ #&2s   0: AAc                 l    t          | j                  j        }d| j         d| }|d| j         z  }|S )NzHTTP Error: z - z	
Detail: )r   r#   phraser   )r$   status_code_meaningformatted_messages      r'   __str__zMaritalkHTTPError.__str__)   sL    ()9::AU4+;UU@SUU8$,888      )__name__
__module____qualname__r   r(   strr-    r.   r'   r   r      sQ        3H 3 3 3 3 3 ! ! ! ! ! ! !r.   r   c                      e Zd ZU dZeed<   	 eed<   	  eddd          Zeed<   	  ed	d
          Z	e
ed<   	  ed          Zeed<   	  eddd          Zeed<   	 edefd            Zdee         deeeeeeeeeeef         f                  f         f                  fdZ	 	 d!dee         deee                  dee         dedef
dZ	 	 d!dee         deee                  dee         dedef
dZ	 	 d!dee         deee                  dee         dedee         f
dZ	 	 d!dee         deee                  dee         dedee         f
dZ	 	 d!dee         deee                  dee         dede f
dZ!	 	 d!dee         deee                  dee         dede f
dZ"edeeef         fd             Z#dS )"ChatMaritalka]  `MariTalk` Chat models API.

    This class allows interacting with the MariTalk chatbot API.
    To use it, you must provide an API key either through the constructor.

    Example:
        .. code-block:: python

            from langchain_community.chat_models import ChatMaritalk
            chat = ChatMaritalk(api_key="your_api_key_here")
    api_keymodelgffffff?g        g      ?)defaultgtlttemperaturei   r   )r8   r9   
max_tokensT)r8   	do_samplegffffff?top_pr   c                     dS )z&Identifies the LLM type as 'maritalk'.maritalkr3   r$   s    r'   	_llm_typezChatMaritalk._llm_typeV   s	     zr.   messagesc                     g }|D ]f}t          |t                    rd}n/t          |t                    rd}nt          |t                    rd}|                    ||j        d           g|S )a>  
        Parses messages from LangChain's format to the format expected by
        the MariTalk API.

        Parameters:
            messages (List[BaseMessage]): A list of messages in LangChain
            format to be parsed.

        Returns:
            A list of messages formatted for the MariTalk API.
        user	assistantsystem)rolecontent)
isinstancer   r   r   appendrI   )r$   rC   parsed_messagesr   rH   s        r'   parse_messages_for_modelz%ChatMaritalk.parse_messages_for_model[   s      	O 	OG'<00  GY//  "G]33  ""DW_#M#MNNNNr.   Nstoprun_managerkwargsc                 H   d}dd| j          i}||ng }|                     |          }|| j        | j        | j        | j        | j        |d|}	t          j        ||	|          }
|
j	        r(|

                                                    dd          S t          |
          )	a  
        Sends the parsed messages to the MariTalk API and returns the generated
        response or an error message.

        This method makes an HTTP POST request to the MariTalk API with the
        provided messages and other parameters.
        If the request is successful and the API returns a response,
        this method returns a string containing the answer.
        If the request is rate-limited or encounters another error,
        it returns a string with the error message.

        Parameters:
            messages (List[BaseMessage]): Messages to send to the model.
            stop (Optional[List[str]]): Tokens that will signal the model
                to stop generating further tokens.

        Returns:
            str: If the API call is successful, returns the answer.
                 If an error occurs (e.g., rate limiting), returns a string
                 describing the error.
        +https://chat.maritaca.ai/api/chat/inferenceauthorizationKey NrC   r7   r=   r<   r;   r>   stopping_tokens)r    headersanswerNo answer found)r6   rM   r7   r=   r<   r;   r>   requestspostokr    getr   )r$   rC   rN   rO   rP   urlrW   rV   rL   dataresponses              r'   _callzChatMaritalk._callv   s    8 <"$94<$9$9:"&"2$$77AA (Z/+Z.	
 	
 	
 =4AAA; 	.==??&&x1BCCC#H---r.   c                 $  K   	 ddl }d}dd| j         i}||ng }|                     |          }	|	| j        | j        | j        | j        | j        |d|}
|                                4 d{V }|	                    ||
|d           d{V }ddd          d{V  n# 1 d{V swxY w Y   |j
        dk    r(|                                                    d	d
          S t          |          # t          $ r t          d          w xY w)a  
        Asynchronously sends the parsed messages to the MariTalk API and returns
        the generated response or an error message.

        This method makes an HTTP POST request to the MariTalk API with the
        provided messages and other parameters using async I/O.
        If the request is successful and the API returns a response,
        this method returns a string containing the answer.
        If the request is rate-limited or encounters another error,
        it returns a string with the error message.
        r   NrR   rS   rT   rU   )r    rW   timeout   rX   rY   RCould not import httpx python package. Please install it with `pip install httpx`.)httpxr6   rM   r7   r=   r<   r;   r>   AsyncClientr[   r#   r    r]   r   ImportError)r$   rC   rN   rO   rP   rf   r^   rW   rV   rL   r_   clientr`   s                r'   _acallzChatMaritalk._acall   s     $"	LLL?C&(=t|(=(=>G&*&6ddBO";;HEEO ,!^"o#/#2	 	 	D ((**       f!'dGT "- " "                                
 #s**}}**85FGGG'111 	 	 	>  	s6   A,C5 0 B"C5 "
B,,C5 /B,05C5 &C5 5Dc           	   +     K   dd| j          i}||ng }|                     |          }|| j        | j        | j        | j        | j        |dd|}t          j        dt          j
        |          |d          }	|	j        r|	                                D ]}
|
                    d          r|
                    dd                              d	          }|r[t          j        |          }d
|v rC|d
         }t#          t%          |                    }|r|                    ||           |V  d S t)          |	          )NAuthorizationrT   TrC   r7   r=   r<   r;   r>   rV   streamrR   )r_   rW   rn   s   data: r.   zutf-8r"   rI   r   chunk)r6   rM   r7   r=   r<   r;   r>   rZ   r[   r    dumpsr\   
iter_lines
startswithreplacedecodeloadsr   r   on_llm_new_tokenr   )r$   rC   rN   rO   rP   rW   rV   rL   r_   r`   lineresponse_dataparsed_datadeltarr   s                  r'   _streamzChatMaritalk._stream   s      #$94<$9$9:"&"2$$77AA (Z/+Z.

 

 

 =9D!!	
 
 
 ; 	. ++-- ( (??9-- ($(LLC$@$@$G$G$P$PM$ 	(&*j&?&?![00$/$7E$7(6u(E(E(E% % %E  + Q + < <U% < P P P"'KKK( ( $H---r.   c           	       K   	 dd l }dd| j         i}||ng }|                     |          }|| j        | j        | j        | j        | j        |dd|}	|                                4 d {V }
|
	                    ddt          j        |	          |d           4 d {V 	 }|j        d	k    r|                                2 3 d {V }|                    d
          rz|                    d
d          }|rbt          j        |          }d|v rJ|d         }t#          t%          |                    }|r|                    ||           d {V  |W V  6 nt)          |          	 d d d           d {V  n# 1 d {V swxY w Y   d d d           d {V  d S # 1 d {V swxY w Y   d S # t*          $ r t+          d          w xY w)Nr   rl   rT   Trm   POSTrR   )r_   rW   rc   rd   zdata:  r"   ro   rp   rq   re   )rf   r6   rM   r7   r=   r<   r;   r>   rg   rn   r    rs   r#   aiter_linesru   rv   rx   r   r   ry   r   rh   )r$   rC   rN   rO   rP   rf   rW   rV   rL   r_   ri   r`   rz   r{   r|   r}   rr   s                    r'   _astreamzChatMaritalk._astream  s     4	LLL&(=t|(=(=>G&*&6ddBO";;HEEO ,!^"o#/#2
 
 
D ((** : : : : : : :f!==AD))#  )   : : : : : : : : +s22*2*>*>*@*@ 4 4 4 4 4 4 4$#x88 404Xr0J0J#0 !426*]2K2KK'-'<'<0;F0C0C4B54Q4Q4Q1* 1* 1* ,7 ).2=2N2N05U 3O 3. 3. -. -. -. -. -. -. -. /4 +A*@" 099993: : : : : : : : : : : : : : : : : : : : : : : : : : :: : : : : : : : : : : : : : : : : : : : : : : : : : : : : :8  	 	 	>  	sa   A+F5 /3F"# E>E	B"E>,F">
F	F"F	F"F5 "
F,,F5 /F,0F5 5Gc                      | j         |f||d|}t          |          }t          |          }t          |g          S N)rN   rO   ro   rp   )generations)ra   r   r   r   r$   rC   rN   rO   rP   
output_strr   
generations           r'   	_generatezChatMaritalk._generateN  sX      TZWtWWPVWW
J///#G444
zl3333r.   c                    K    | j         |f||d| d {V }t          |          }t          |          }t          |g          S r   )rj   r   r   r   r   s           r'   
_ageneratezChatMaritalk._agenerateZ  s       '4;
[
 
<B
 
 
 
 
 
 
 

 J///#G444
zl3333r.   c                 8    | j         | j        | j        | j        dS )z
        Identifies the key parameters of the chat model for logging
        or tracking purposes.

        Returns:
            A dictionary of the key configuration parameters.
        r7   r;   r>   r<   r   rA   s    r'   _identifying_paramsz ChatMaritalk._identifying_paramsh  s(     Z+Z/	
 
 	
r.   )NN)$r/   r0   r1   __doc__r2   __annotations__r   r;   floatr<   intr=   boolr>   propertyrB   r   r   r   r
   r   rM   r	   r   ra   r   rj   r   r   r~   r   r   r   r   r   r   r3   r.   r'   r5   r5   0   s        
 
 LLL JJJ, sss;;;K;;;2 eCA...J...@eD)))It)))?5##666E56665 3    X[)	d3c4c4S>.A(B#CCDDE	F   < %):>	2. 2.{#2. tCy!2. 67	2.
 2. 
2. 2. 2. 2.n %)?C	4 4{#4 tCy!4 ;<	4
 4 
4 4 4 4r %):>	/. /.{#/. tCy!/. 67	/.
 /. 
%	&/. /. /. /.h %)?C	; ;{#; tCy!; ;<	;
 ; 
*	+; ; ; ;@ %):>	
4 
4{#
4 tCy!
4 67	
4
 
4 

4 
4 
4 
4 %)?C	4 4{#4 tCy!4 ;<	4
 4 
4 4 4 4 
T#s(^ 
 
 
 X
 
 
r.   r5   )"r    httpr   typingr   r   r   r   r   r	   r
   rZ   langchain_core.callbacksr   r   *langchain_core.language_models.chat_modelsr   langchain_core.messagesr   r   r   r   r   langchain_core.outputsr   r   r   pydanticr   r   requests.exceptionsr   r   r5   r3   r.   r'   <module>r      s          L L L L L L L L L L L L L L L L L L         E D D D D D              S R R R R R R R R R             ) ) ) ) ) )! ! ! ! !	 ! ! !0F
 F
 F
 F
 F
= F
 F
 F
 F
 F
r.   