
    NgD                        d dl Z d dlZd dlmZmZmZmZmZmZm	Z	m
Z
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 d dlmZmZmZmZmZmZmZmZm Z m!Z!m"Z"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-m.Z.m/Z/ d dl0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8m9Z9m:Z:  ej;        e<          Z= G d de          Z>de$de?fdZ@de!de?fdZAdS )    N)AnyCallableDictIteratorListLiteralMappingOptionalSequenceTypeUnioncast)urlparse)CallbackManagerForLLMRun)BaseChatModel)LanguageModelInput)	AIMessageAIMessageChunkBaseMessageBaseMessageChunkChatMessageChatMessageChunkFunctionMessageHumanMessageHumanMessageChunkInvalidToolCallSystemMessageSystemMessageChunkToolCallToolMessageToolMessageChunk)tool_call_chunk)make_invalid_tool_callparse_tool_call)ChatGenerationChatGenerationChunk
ChatResult)RunnableRunnableConfig)BaseToolconvert_to_openai_tool)	BaseModelFieldPrivateAttrc                       e Zd ZU dZeed<   	 eed<   	 dZeed<   	 dZe	ed<   	 dZ
eee                  ed	<   	 dZee	         ed
<   	  ee          Zeed<   	  e            Zeed<   def fdZedefd            Zd.dZedeeef         fd            Z	 d/dee         d	eee                  dedeeef         fdZ	 	 d0dee         d	eee                  dee         dedef
dZ	 d/dddedee          d	eee                  dede!e"         f
 fdZ#	 	 d0dee         d	eee                  dee         dede!e$         f
dZ%edeeef         fd            Z&	 d/d	eee                  dedeeef         f fdZ'edefd            Z(e)d e*eef         defd!            Z+e)d e*eef         d"ede"fd#            Z,e)d.d$            Z-e)d%edefd&            Z.e)d'e*eef         defd(            Z/dd)d*e0e1eeef         e2e3         e4e5f                  d+ee1eee6d,         e7f                  dede8eef         f fd-Z9 xZ:S )1
ChatMlflowa  `MLflow` chat models API.

    To use, you should have the `mlflow[genai]` python package installed.
    For more information, see https://mlflow.org/docs/latest/llms/deployments.

    Example:
        .. code-block:: python

            from langchain_community.chat_models import ChatMlflow

            chat = ChatMlflow(
                target_uri="http://localhost:5000",
                endpoint="chat",
                temperature=0.1,
            )
    endpoint
target_urig        temperature   nNstop
max_tokens)default_factoryextra_params_clientkwargsc                      t                      j        di | |                                  	 ddlm}  || j                  | _        d S # t          $ r}t          d| j         d          |d }~ww xY w)Nr   )get_deploy_clientz;Failed to create the client. Please run `pip install mlflowz#` to install required dependencies. )	super__init___validate_urimlflow.deploymentsr>   r3   r;   ImportError_mlflow_extras)selfr<   r>   e	__class__s       b/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chat_models/mlflow.pyrA   zChatMlflow.__init__[   s    ""6"""		<<<<<<,,T_==DLLL 	 	 	)151D) ) )  		s   A 
A5A00A5returnc                     dS )Nz[genai]r?   rF   s    rI   rE   zChatMlflow._mlflow_extrasi   s    y    c                     | j         dk    rd S g d}t          | j                   j        |vrt          d| j          d| d          d S )N
databricks)httphttpsrO   zInvalid target URI: z. The scheme must be one of .)r3   r   scheme
ValueError)rF   alloweds     rI   rB   zChatMlflow._validate_urim   sv    ?l**F111DO$$+7::8t 8 8-48 8 8   ;:rM   c                 `    | j         | j        | j        | j        | j        | j        | j        d}|S )Nr3   r2   r4   r6   r7   r8   r:   rW   )rF   paramss     rI   _default_paramszChatMlflow._default_paramsw   s<     /+I/ -"
 "
 rM   messagesc                     d |D             }|| j         | j        d| j        |}| j        p|x}r||d<   | j        
| j        |d<   |S )Nc                 B    g | ]}t                               |          S r?   )r1   _convert_message_to_dict).0messages     rI   
<listcomp>z.ChatMlflow._prepare_inputs.<locals>.<listcomp>   s3     
 
 
=DJ//88
 
 
rM   )rZ   r4   r6   r7   r8   )r4   r6   r:   r7   r8   )rF   rZ   r7   r<   message_dictsdatas         rI   _prepare_inputszChatMlflow._prepare_inputs   s    
 
HP
 
 
 &+ 
  
 	 

  
 9$$4 	 DL?&!%DrM   run_managerc                      | j         ||fi |}| j                            | j        |          }t                              |          S )Nr2   inputs)rc   r;   predictr2   r1   _create_chat_result)rF   rZ   r7   rd   r<   rb   resps          rI   	_generatezChatMlflow._generate   s_     $t#
 
 
 

 |##T]4#HH--d333rM   )r7   inputconfigc          	   +      K   t          | j        d          s(t          t           | j        |f||d|          V  d S  t                      j        ||fd|i|E d {V  d S )Npredict_stream)rm   r7   r7   )hasattrr;   r   r   invoker@   stream)rF   rl   rm   r7   r<   rH   s        rI   rr   zChatMlflow.stream   s       t|%566 	J  +$+e"XF"X"XQW"X"X       &uww~eVII$I&IIIIIIIIIIIrM   c              +     K    | j         ||fi |}| j                            | j        |          }d }|D ]}|d         r|d         d         }	|	d         }
||
                    d          }t
                              |
|          }i }|	                    d          x}r||d<   |	                    d          x}r||d<   t          ||pd           }|r|                    |j	        ||	           |V  Ìd S )
Nrf   choicesr   deltarolefinish_reasonlogprobsr_   generation_info)chunkrx   )
rc   r;   ro   r2   getr1   _convert_delta_to_message_chunkr&   on_llm_new_tokentext)rF   rZ   r7   rd   r<   rb   
chunk_iterfirst_chunk_roler{   choicechunk_deltachunk_messagerz   rw   rx   s                  rI   _streamzChatMlflow._stream   su      $t#
 
 
 
 \00$-PT0UU
 	 	EY y)!,$Wo#+'2v'>'>$ * J J!1! ! #%$*JJ$?$??= E7DOO4%zz*5558 ;2:OJ/+)?;Rd    00
%( 1     =	 	rM   c                     | j         S N)rY   rL   s    rI   _identifying_paramszChatMlflow._identifying_params   s    ##rM   c                 L    i | j          t                      j        dd|i|S )z>Get the parameters used to invoke the model FOR THE CALLBACKS.r7   r?   )rY   r@   _get_invocation_params)rF   r7   r<   rH   s      rI   r   z!ChatMlflow._get_invocation_params   s<    
"
,egg,AA$A&AA
 	
rM   c                     dS )zReturn type of chat model.zmlflow-chatr?   rL   s    rI   	_llm_typezChatMlflow._llm_type   s	     }rM   _dictc           
      d   | d         }t          t          |                     d                    }|dk    rt          |          S |dk    r|pd}i }g }g }|                     d          x}rv||d<   |D ]n}	 |                    t          |d	                     (# t          $ r:}|                    t          |t          |                               Y d }~gd }~ww xY wt          |||                     d
          ||          S |dk    rt          |          S t          ||          S )Nrv   contentuserr   	assistant 
tool_callsT)	return_idid)r   additional_kwargsr   r   invalid_tool_callssystemr   rv   )r   strr|   r   appendr$   	Exceptionr#   r   r   r   )	r   rv   r   r   r   r   raw_tool_callsraw_tool_callrG   s	            rI   _convert_dict_to_messagez#ChatMlflow._convert_dict_to_message   s   V}sEIIi00116>>0000[  mG&(J!#!&<!8!88~ 
2@!,/%3  M"))+MTJJJ    %   *112=#a&&II        "399T??%#5    X 1111wT::::s   8$B
C!'0CC!default_rolec                    |                      d|          }|                      d          pd}|dk    rt          |          S |dk    rdi }g }|                      d          x}r#||d<   	 d |D             }n# t          $ r Y nw xY wt          |||                      d	          |
          S |dk    rt	          |          S |dk    r+t          || d         |                      d	                    S t          ||          S )Nrv   r   r   r   r   r   r   c           	          g | ]`}t          |d                              d          |d                              d          |                    d          |d                   aS )functionname	argumentsr   index)r   argsr   r   )r"   r|   )r^   rtcs     rI   r`   z>ChatMlflow._convert_delta_to_message_chunk.<locals>.<listcomp>.  sw     ( ( (   (!$Z!4!4V!<!<!$Z!4!4[!A!A"wwt}}"%g,	  ( ( (rM   r   )r   r   r   tool_call_chunksr   tooltool_call_id)r   r   r   r   )r|   r   KeyErrorr   r   r!   r   )r   r   rv   r   r   r   r   s          rI   r}   z*ChatMlflow._convert_delta_to_message_chunk   sd    yy..))I&&,"6>>$W5555[  &(!!&<!8!88~ 2@!,/( ( $2( ( ($$     D!"399T??!1	    X%g6666V^^#eN.C		RV    $G$????s   +A8 8
BBc                       t          d          )N~Function messages are not supported by Databricks. Please create a feature request at https://github.com/mlflow/mlflow/issues.)rT   r?   rM   rI   _raise_functions_not_supportedz)ChatMlflow._raise_functions_not_supportedH  s    T
 
 	
rM   r_   c                    d| j         i}| j        p| j                            d          x}||d<   t	          | t
                    r| j        |d<   nMt	          | t                    rd|d<   n1t	          | t                    rd|d<   | j	        s| j
        r'd | j	        D             d | j
        D             z   |d<   n6d| j        v r,| j        d         |d<   h d	fd
|d         D             |d<   n	 d|v r|d         pd |d<   nt	          | t                    rd|d<   nt	          | t                    r4d|d<   | j        |d<   h dfd|                                D             }n6t	          | t                    rt!          d          t!          d|            d| j        v rt"                                           |S )Nr   r   rv   r   r   c                 ,    g | ]}t          |          S r?   )!_lc_tool_call_to_openai_tool_callr^   tcs     rI   r`   z7ChatMlflow._convert_message_to_dict.<locals>.<listcomp>[  s.     . . .>@5b99. . .rM   c                 ,    g | ]}t          |          S r?   ))_lc_invalid_tool_call_to_openai_tool_callr   s     rI   r`   z7ChatMlflow._convert_message_to_dict.<locals>.<listcomp>]  s0        >bAA  rM   r   >   r   typer   c                 P    g | ]"}fd |                                 D             #S )c                 $    i | ]\  }}|v 	||S r?   r?   )r^   kvtool_call_supported_propss      rI   
<dictcomp>zBChatMlflow._convert_message_to_dict.<locals>.<listcomp>.<dictcomp>e  s5        Aq 999 1999rM   )items)r^   	tool_callr   s     rI   r`   z7ChatMlflow._convert_message_to_dict.<locals>.<listcomp>d  sV     . . . "   $-OO$5$5  . . .rM   r   r   r   >   rv   r   r   c                 $    i | ]\  }}|v 	||S r?   r?   )r^   r   r   supported_propss      rI   r   z7ChatMlflow._convert_message_to_dict.<locals>.<dictcomp>w  s0       Ao9M9M19M9M9MrM   r   zGot unknown message type: function_call)r   r   r   r|   
isinstancer   rv   r   r   r   r   r   r    r   r   r   rT   r1   r   )r_   message_dictr   r   r   s      @@rI   r]   z#ChatMlflow._convert_message_to_dictO  s   !7?3LIG$=$A$A&$I$IIDV#'L g{++ ,	E#*<L  .. *	E#)L  ++ (	E#.L ! W%? . .DKDV. . . %8  .\** !:::-4-F|-T\*,F,F,F). . . . &2,%?. . .\** |++*6y*A*ITY'// 	E#+L  -- 	E#)L +2+?L(AAAO   !-!3!3!5!5  LL 11 	EX  
 C'CCDDDg77755777rM   responsec                 "   g }| d         D ]^}t                               |d                   }|                    di           }t          ||          }|                    |           _|                     di           }t          ||          S )Nrt   r_   usagery   )generations
llm_output)r1   r   r|   r%   r   r'   )r   r   r   r_   r   gens         rI   ri   zChatMlflow._create_chat_result  s    y) 	$ 	$F 99&:KLLGJJw++E  %  C s####Wb))keDDDDrM   )tool_choicetoolsr   )autononerequiredanyc                n   d |D             }rt          t                    rdvrddidnet          t                    r>d |D             }t          fd|D                       st	          d d	| d
          nt	          d           |d<    t                      j        dd|i|S )a  Bind tool-like objects to this chat model.

        Assumes model is compatible with OpenAI tool-calling API.

        Args:
            tools: A list of tool definitions to bind to this chat model.
                Can be  a dictionary, pydantic model, callable, or BaseTool. Pydantic
                models, callables, and BaseTools will be automatically converted to
                their schema dictionary representation.
            tool_choice: Which tool to require the model to call.
                Options are:
                name of the tool (str): calls corresponding tool;
                "auto": automatically selects a tool (including no tool);
                "none": model does not generate any tool calls and instead must
                    generate a standard assistant message;
                "required": the model picks the most relevant tool in tools and
                    must generate a tool call;

                or a dict of the form:
                {"type": "function", "function": {"name": <<tool_name>>}}.
            **kwargs: Any additional parameters to pass to the
                :class:`~langchain.runnable.Runnable` constructor.
        c                 ,    g | ]}t          |          S r?   r+   )r^   r   s     rI   r`   z)ChatMlflow.bind_tools.<locals>.<listcomp>  s!    JJJD1$77JJJrM   )r   r   r   r   r   )r   r   c                 *    g | ]}|d          d         S )r   r   r?   )r^   formatted_tools     rI   r`   z)ChatMlflow.bind_tools.<locals>.<listcomp>  s2       & #:.v6  rM   c              3   <   K   | ]}|d          d         k    V  dS )r   r   Nr?   )r^   	tool_namer   s     rI   	<genexpr>z(ChatMlflow.bind_tools.<locals>.<genexpr>  sF        ! Z!8!@@     rM   zTool choice z1 was specified, but the only provided tools were rR   zEUnrecognized tool_choice type. Expected str, bool or dict. Received: r   r   r?   )r   r   dictr   rT   r@   bind)rF   r   r   r<   formatted_tools
tool_namesrH   s     `   rI   
bind_toolszChatMlflow.bind_tools  sT   @ KJEJJJ 	0+s++ &BBB *%+[$9# #K K..  *9  
     %/      %={ = =/9= = =  	 !/!,/ /   %0F=!uww|<</<V<<<rM   )rJ   Nr   )NN);__name__
__module____qualname____doc__r   __annotations__r4   floatr6   intr7   r
   r   r8   r.   r   r:   r/   r;   r   rA   propertyrE   rB   r   rY   r   rc   r   r'   rk   r   r)   r   r   rr   r&   r   r   r   r   staticmethodr	   r   r}   r   r]   ri   r   r   r   r-   r   r*   r   boolr(   r   __classcell__)rH   s   @rI   r1   r1   9   sa         " MMMOOO K#AsJJJ7 $D(49
$$$ $J$$$3t444L$4447;==GS              X    
c3h 
 
 
 X
 %) {# tCy! 	
 
c3h   4 %):>	4 4{#4 tCy!4 67	4
 4 
4 4 4 4$ ,0J
 %)J J J!J (J
 tCy!J J 
"	#J J J J J J, %):>	- -{#- tCy!- 67	-
 - 
%	&- - - -^ $T#s(^ $ $ $ X$ +/
 
T#Y'
:=
	c3h
 
 
 
 
 
 3    X ;S(9 ;k ; ; ; \;B %@sCx %@03%@	%@ %@ %@ \%@N 
 
 
 \
 4+ 4$ 4 4 4 \4l Egc3h&7 EJ E E E \E( <= <= <=d38nd9oxQRS<= $W%FGMN
	<= <= 
$k1	2<= <= <= <= <= <= <= <= <= <=rM   r1   r   rJ   c                 \    d| d         | d         t          j        | d                   ddS Nr   r   r   r   )r   r   )r   r   r   )jsondumps)r   s    rI   r   r     s?    of%If$566
 
  rM   invalid_tool_callc                 8    d| d         | d         | d         ddS r   r?   )r   s    rI   r   r     s8     %%f-*62
 
  rM   )Br   loggingtypingr   r   r   r   r   r   r	   r
   r   r   r   r   urllib.parser   langchain_core.callbacksr   langchain_core.language_modelsr   #langchain_core.language_models.baser   langchain_core.messagesr   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   langchain_core.messages.toolr"   *langchain_core.output_parsers.openai_toolsr#   r$   langchain_core.outputsr%   r&   r'   langchain_core.runnablesr(   r)   langchain_core.toolsr*   %langchain_core.utils.function_callingr,   pydanticr-   r.   r/   	getLoggerr   loggerr1   r   r   r   r?   rM   rI   <module>r      s                                " ! ! ! ! ! = = = = = = 8 8 8 8 8 8 B B B B B B                                 " 9 8 8 8 8 8        S R R R R R R R R R = = = = = = = = ) ) ) ) ) ) H H H H H H          
	8	$	$X= X= X= X= X= X= X= X=v d    
&
	
 
 
 
 
 
rM   