
    NgfQ                        d dl Z d dlZd dlZd dlmZmZ d dlmZmZm	Z	m
Z
mZmZ d dl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 dgZ G d	 d
ee          Zde	eef         defdZde	eef         defdZde	eef         defdZ G d de          Z  G d de          Z!defdZ"defdZ#defdZ$dede%fdZ&dedee%         defdZ'dedefdZ( eddd            G d! de                      Z)dS )"    N)ABCabstractmethod)AnyCallableDictListMappingOptional)
deprecated)CallbackManagerForLLMRun)LLM)	BaseModel
ConfigDictFieldPrivateAttrmodel_validator
Databricksc            	           e Zd ZU dZeed<   eed<   dedededefdZdedefd	Zdededefd
Z	e
	 ddedeedef                  defd            Zedefd            ZdS )_DatabricksClientBasez0A base JSON API client that talks to Databricks.api_url	api_tokenmethodurlrequestreturnc                     dd| j          i}t          j        ||||          }|j        st	          d|j         d|j                   |                                S )NAuthorizationzBearer )r   r   headersjsonzHTTP z error: )r   requestsr   ok
ValueErrorstatus_codetextr   )selfr   r   r   r   responses         _/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/llms/databricks.pyr   z_DatabricksClientBase.request   sv    "$>dn$>$>?#sG'
 
 
 { 	TRX%9RR8=RRSSS}}    c                 0    |                      d|d           S )NGETr   )r%   r   s     r'   _getz_DatabricksClientBase._get&   s    ||E3---r(   c                 0    |                      d||          S )NPOSTr+   )r%   r   r   s      r'   _postz_DatabricksClientBase._post)   s    ||FC111r(   Ntransform_output_fn.c                     d S N )r%   r   r0   s      r'   postz_DatabricksClientBase.post,   s	     cr(   c                     dS )NFr3   r%   s    r'   llmz_DatabricksClientBase.llm1   s    ur(   r2   )__name__
__module____qualname____doc__str__annotations__r   r   r,   r/   r   r
   r   r4   propertyboolr7   r3   r(   r'   r   r      s        ::LLLNNNc  c c    . . . . . .2 2s 2s 2 2 2 2 PT 19(38:L1M	   ^ T    X  r(   r   r&   r   c                 *    | d         d         d         S )Nchoicesr   r$   r3   r&   s    r'   _transform_completionsrC   6   s    Iq!&))r(   c                 *    | d         d         d         S )N
candidatesr   r$   r3   rB   s    r'   _transform_llama2_chatrF   :   s    L!!$V,,r(   c                 6    | d         d         d         d         S )NrA   r   messagecontentr3   rB   s    r'   _transform_chatrJ   >   s    Iq!),Y77r(   c                   "    e Zd ZU dZeed<   eed<   eed<   dZeed<   dZe	ed<   dZ
ee         ed	<   d
ef fdZede	fd            Z ed          edeeef         defd                        Z	 ddedeedef                  defdZ xZS ) _DatabricksServingEndpointClientz:An API client that talks to a Databricks serving endpoint.hostendpoint_namedatabricks_uriNclientFexternal_or_foundationtaskdatac                     t                      j        di | 	 ddlm}  || j                  | _        n"# t          $ r}t          d          |d }~ww xY w| j                            | j                  }|	                    dd          
                                dv | _        | j        |	                    d          | _        d S d S )	Nr   )get_deploy_clientzMFailed to create the client. Please install mlflow with `pip install mlflow`.endpoint_type )external_modelfoundation_model_apirR   r3   )super__init__mlflow.deploymentsrU   rO   rP   ImportErrorget_endpointrN   getlowerrQ   rR   )r%   rS   rU   eendpoint	__class__s        r'   r[   z)_DatabricksServingEndpointClient.__init__L   s      4   	<<<<<<++D,?@@DKK 	 	 	C  	 ;++D,>??&.ll?B&G&G&M&M&O&O T
 '
# 9 V,,DIII s   8 
AAAr   c                     | j         dv S )N)llm/v1/chatllm/v1/completionsllama2/chat)rR   r6   s    r'   r7   z$_DatabricksServingEndpointClient.llma   s    yPPPr(   beforemodevaluesc                 J    d|vr|d         }|d         }d| d| d}||d<   |S )Nr   rM   rN   https://z/serving-endpoints/z/invocationsr3   )clsrk   rM   rN   r   s        r'   set_api_urlz,_DatabricksServingEndpointClient.set_api_urle   sI     F""&>D"?3MUUU-UUUG 'F9r(   r   r0   .c                    | j         rd| j                            | j        |          }|r ||          S | j        dk    rt          |          S | j        dk    rt          |          S |S d|gi}| j                            | j        |          }|d         }t          |t                    r|d         n|}| j        dk    rt          |          S |r ||          n|S )N)rb   inputsre   rf   dataframe_recordspredictionsr   rg   )
rQ   rP   predictrN   rR   rJ   rC   
isinstancelistrF   )r%   r   r0   respwrapped_requestr&   predspreds           r'   r4   z%_DatabricksServingEndpointClient.posto   s    & 	N;&&0B7&SSD" 1**4000yM))&t,,,222-d333K  3WI>O{**+O +  H ]+E)%66A588EDyM))-d3330CM&&t,,,Mr(   r2   )r8   r9   r:   r;   r<   r=   rP   r   rQ   r?   rR   r
   r[   r>   r7   r   classmethodr   ro   r   r4   __classcell__rc   s   @r'   rL   rL   B   sn        DD
IIIFC#(D(((D(3--s - - - - - -* QT Q Q Q XQ _(###c3h C    [ $# QUN NN19(38:L1MN	N N N N N N N Nr(   rL   c                       e Zd ZU dZeed<   eed<   eed<    ed          edeee	f         de	fd	                        Z
	 dde	deedef                  de	fdZd
S )#_DatabricksClusterDriverProxyClientzBAn API client that talks to a Databricks cluster driver proxy app.rM   
cluster_idcluster_driver_portrh   ri   rk   r   c                 ^    d|vr(|d         }|d         }|d         }d| d| d| }||d<   |S )Nr   rM   r   r   rm   z/driver-proxy-api/o/0//r3   )rn   rk   rM   r   portr   s         r'   ro   z/_DatabricksClusterDriverProxyClient.set_api_url   sY     F""&>D-J/0DPPPZPP$PPG 'F9r(   Nr   r0   .c                 V    |                      | j        |          }|r ||          n|S r2   )r/   r   )r%   r   r0   rw   s       r'   r4   z(_DatabricksClusterDriverProxyClient.post   s5     zz$,00,?I""4(((TIr(   r2   )r8   r9   r:   r;   r<   r=   r   r{   r   r   ro   r
   r   r4   r3   r(   r'   r   r      s         LL
IIIOOO_(###c3h C    [ $# QUJ JJ19(38:L1MJ	J J J J J Jr(   r   c                  ^    	 ddl m}   |             S # t          $ r t          d          w xY w)zgGet the notebook REPL context if running inside a Databricks notebook.
    Returns None otherwise.
    r   get_contextzBCannot access dbruntime, not running inside a Databricks notebook.)!dbruntime.databricks_repl_contextr   r]   r   s    r'   get_repl_contextr      sU    
AAAAAA{}} 
 
 
P
 
 	

s    ,c                  <   t          j        d          } | sJ	 t                      j        } | st	          d          n$# t
          $ r}t	          d|           d}~ww xY w|                     d                              d                              d          } | S )z{Get the default Databricks workspace hostname.
    Raises an error if the hostname cannot be automatically determined.
    DATABRICKS_HOSTz(context doesn't contain browserHostName.zshost was not set and cannot be automatically inferred. Set environment variable 'DATABRICKS_HOST'. Received error: Nrm   zhttp://r   )osgetenvr   browserHostNamer"   	Exceptionlstriprstrip)rM   ra   s     r'   get_default_hostr      s     9&''D 		#%%5D M !KLLLM 	 	 	OKLO O  	 ;;z"")))44;;C@@DKs   $= 
AAAc                      t          j        d          x} r| S 	 t                      j        } | st	          d          n$# t
          $ r}t	          d|           d}~ww xY w| S )z{Get the default Databricks personal access token.
    Raises an error if the token cannot be automatically determined.
    DATABRICKS_TOKENz!context doesn't contain apiToken.zyapi_token was not set and cannot be automatically inferred. Set environment variable 'DATABRICKS_TOKEN'. Received error: N)r   r   r   apiTokenr"   r   )r   ra   s     r'   get_default_api_tokenr      s     I0111y 
$&&/	 	B@AAA	B 
 
 
LHIL L
 
 	

 s   $? 
A 	AA rS   c                 x    t          | t                    sdS d}t          t          j        ||                     S )zJChecks if a data is a valid hexadecimal string using a regular expression.Fz^[0-9a-fA-F]+$)ru   r<   r?   rematch)rS   patterns     r'   _is_hex_stringr      s8    dC   uG$''(((r(   allow_dangerous_deserializationc                    |st          d          	 ddl}n$# t          $ r}t          d|           d}~ww xY w	 |                    t                              |                     S # t          $ r}t          d|           d}~ww xY w)z3Loads a pickled function from a hexadecimal string.aW  This code relies on the pickle module. You will need to set allow_dangerous_deserialization=True if you want to opt-in to allow deserialization of data using pickle.Data can be compromised by a malicious actor if not handled properly to include a malicious payload that when deserialized with pickle can execute arbitrary code on your machine.r   N*Please install cloudpickle>=2.0.0. Error: zFFailed to load the pickled function from a hexadecimal string. Error: )r"   cloudpickler   loadsbytesfromhex)rS   r   r   ra   s       r'    _load_pickled_fn_from_hex_stringr      s     + 	
A
 
 	
K K K KIaIIJJJK
  t!4!4555 
 
 
XUVXX
 
 	

s'    
949,A* *
B4BBfnc                     	 ddl }n$# t          $ r}t          d|           d}~ww xY w	 |                    |                                           S # t          $ r}t          d|           d}~ww xY w)z6Pickles a function and returns the hexadecimal string.r   Nr   zFailed to pickle the function: )r   r   r"   dumpshex)r   r   ra   s      r'   _pickle_fn_to_hex_stringr      s    K K K KIaIIJJJK@  $$((*** @ @ @>1>>???@s'    
(#(&A 
A4A//A4z0.3.3z1.0z#langchain_databricks.ChatDatabricks)sinceremovalalternative_importc                   ~    e Zd ZU dZ ee          Zeed<   	  ee	          Z
eed<   	 dZee         ed<   	 dZee         ed<   	 dZee         ed<   	 dZeeeef                  ed	<   	 dZee         ed
<   	 dZeedef                  ed<   	 dZ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ef         ed<   	 dZee         ed<   	 dZ e!ed<   	  e"            Z#e$ed<    e%d          Z&e'deeef         fd            Z( e)d          e*d eeef         defd!                        Z+d"ef fd#Z,e'deeef         fd$            Z-e'de.eef         fd%            Z/e'defd&            Z0	 	 d+d'edeee                  d(ee1         d)edef
d*Z2 xZ3S ),r   a	  Databricks serving endpoint or a cluster driver proxy app for LLM.

    It supports two endpoint types:

    * **Serving endpoint** (recommended for both production and development).
      We assume that an LLM was deployed to a serving endpoint.
      To wrap it as an LLM you must have "Can Query" permission to the endpoint.
      Set ``endpoint_name`` accordingly and do not set ``cluster_id`` and
      ``cluster_driver_port``.

      If the underlying model is a model registered by MLflow, the expected model
      signature is:

      * inputs::

          [{"name": "prompt", "type": "string"},
           {"name": "stop", "type": "list[string]"}]

      * outputs: ``[{"type": "string"}]``

      If the underlying model is an external or foundation model, the response from the
      endpoint is automatically transformed to the expected format unless
      ``transform_output_fn`` is provided.

    * **Cluster driver proxy app** (recommended for interactive development).
      One can load an LLM on a Databricks interactive cluster and start a local HTTP
      server on the driver node to serve the model at ``/`` using HTTP POST method
      with JSON input/output.
      Please use a port number between ``[3000, 8000]`` and let the server listen to
      the driver IP address or simply ``0.0.0.0`` instead of localhost only.
      To wrap it as an LLM you must have "Can Attach To" permission to the cluster.
      Set ``cluster_id`` and ``cluster_driver_port`` and do not set ``endpoint_name``.
      The expected server schema (using JSON schema) is:

      * inputs::

          {"type": "object",
           "properties": {
              "prompt": {"type": "string"},
              "stop": {"type": "array", "items": {"type": "string"}}},
           "required": ["prompt"]}`

      * outputs: ``{"type": "string"}``

    If the endpoint model signature is different or you want to set extra params,
    you can use `transform_input_fn` and `transform_output_fn` to apply necessary
    transformations before and after the query.
    )default_factoryrM   r   NrN   r   r   model_kwargstransform_input_fn.r0   
databricksrO   g        temperature   nstop
max_tokensextra_paramsrR   Fr   _clientforbid)extrar   c                 h    | j         | j        d}| j        r
| j        |d<   | j        
| j        |d<   |S )N)r   r   r   r   )r   r   r   r   )r%   paramss     r'   _llm_paramszDatabricks._llm_params  sK      +"
 "
 9 	'!YF6N?&#'?F< r(   rh   ri   rk   c                 f   |                     d          }|                     d          }|r|rt          d          |rd |d<   nQ|rnN	 t                      j        x}r||d<   t          d          # t          $ r}t          d|           d }~ww xY w|                     d          }|r|rt          d          |rd |d<   n7|t          d          t          |          d	k    rt          d
|           	 |                     d          x}rd|vs
J d            d|vs
J d            |S )Nr   rN   z-Cannot set both endpoint_name and cluster_id.z"Context doesn't contain clusterId.zuNeither endpoint_name nor cluster_id was set. And the cluster_id cannot be automatically determined. Received error: r   z6Cannot set both endpoint_name and cluster_driver_port.z<Must set cluster_driver_port to connect to a cluster driver.r   zInvalid cluster_driver_port: r   promptz*model_kwargs must not contain key 'prompt'r   z(model_kwargs must not contain key 'stop')r_   r"   r   	clusterIdr   int)rn   rk   r   rN   context_cluster_idra   r   r   s           r'   set_cluster_idzDatabricks.set_cluster_id  s    ZZ--


?33 	- 	LMMM 	#'F<   		)9););)EE% >+=F<( !EFFF    # # #   %jj)>?? 	= 	UVVV 		,0F()) (N   $%%**R=PRRSSS!::n555< 	:,,,; -,, l***9 +**s   
)A3 3
B=BBrS   c                    d|v rBt          |d                   r-t          |d         |                    d                    |d<   d|v rBt          |d                   r-t          |d         |                    d                    |d<    t                      j        d
i | | j        | j        t          d          | j        t          j	        dt                     | j        r4t          | j        | j        | j        | j        | j                  | _        d S | j        r5| j        r.t)          | j        | j        | j        | j                  | _        d S t          d	          )Nr   r   )rS   r   r0   z.Cannot set both extra_params and extra_params.z<model_kwargs is deprecated. Please use extra_params instead.)rM   r   rN   rO   rR   )rM   r   r   r   zDMust specify either endpoint_name or cluster_id/cluster_driver_port.r3   )r   r   r_   rZ   r[   r   r   r"   warningswarnDeprecationWarningrN   rL   rM   r   rO   rR   r   r   r   r   )r%   rS   rc   s     r'   r[   zDatabricks.__init__  s   4''N4@T;U,V,V')I./0451 1* * *D%& !D((^&'.
 .
( +K/00451 1+ + +D&' 	  4   (T->-JMNNN*MN"    	;Y."0#2Y  DLLL _ 
	!9 
	>Y.?$($<	  DLLL V  r(   c                    | j         | j        | j        | j        | j        | j        | j        | j        | j        | j	        | j
        | j        | j        dnt          | j                  | j        dnt          | j                  dS )zReturn default params.N)rM   rN   r   r   rO   r   r   r   r   r   r   rR   r   r0   )rM   rN   r   r   rO   r   r   r   r   r   r   rR   r   r   r0   r6   s    r'   _default_paramszDatabricks._default_params  s     I!//#'#;"1 -+I/ -I&. #'$)$*ABB'/ $(4)$*BCC'
 
 	
r(   c                     | j         S r2   )r   r6   s    r'   _identifying_paramszDatabricks._identifying_params  s    ##r(   c                     dS )zReturn type of llm.r   r3   r6   s    r'   	_llm_typezDatabricks._llm_type  s	     |r(   r   run_managerkwargsc                 :   d|i}| j         j        r|                    | j                   |                    | j        p| j                   |                    |           |r||d<   | j        r | j        di |}| j                             || j                  S )zAQueries the LLM endpoint with the given prompt and stop sequence.r   r   )r0   r3   )	r   r7   updater   r   r   r   r4   r0   )r%   r   r   r   r   r   s         r'   _callzDatabricks._call$  s     $,V"4< 	-NN4+,,,t(=D,=>>>v 	#"GFO" 	9-d-8888G|  d>V WWWr(   )NN)4r8   r9   r:   r;   r   r   rM   r<   r=   r   r   rN   r
   r   r   r   r   r   r   r   r0   rO   r   floatr   r   r   r   r   dictr   rR   r   r?   r   r   r   r   model_configr>   r   r   r{   r   r[   r   r	   r   r   r   r   r|   r}   s   @r'   r   r   
  s        / /b &6777D#777 U+@AAAIsAAA $(M8C='''
 !%J$$$ *.#---
 .2L(4S>*111
 .2*111
 9=(38"45<<< 'NC&&&FK#AsJJJ7 $D(49
$$$ $J$$$3#(5#>#>#>L$sCx.>>>7D(3- -2#T111 &1[]]G"222:  L 	T#s(^ 	 	 	 X	 _(###*DcN *t * * * [ $#*X,s , , , , , ,\ 
c3h 
 
 
 X
0 $WS#X%6 $ $ $ X$ 3    X %):>	X XX tCy!X 67	X
 X 
X X X X X X X Xr(   )*r   r   r   abcr   r   typingr   r   r   r   r	   r
   r    langchain_core._apir   langchain_core.callbacksr   langchain_core.language_modelsr   pydanticr   r   r   r   r   __all__r   r<   rC   rF   rJ   rL   r   r   r   r   r?   r   r   r   r   r3   r(   r'   <module>r      sL   				 				  # # # # # # # # ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?  * * * * * * = = = = = = . . . . . .              .    Is   @*T#s(^ * * * * *-T#s(^ - - - - -8d38n 8 8 8 8 8FN FN FN FN FN'< FN FN FNRJ J J J J*? J J J2
# 
 
 
 
#    (s    &) ) ) ) ) )


08

 
 
 
8
@ 
@c 
@ 
@ 
@ 
@ 
<  
kX kX kX kX kX kX kX 
kX kX kXr(   