
    7|hfQ                        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)y)"    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y)_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                         |j                         S )NAuthorizationzBearer )r   r   headersjsonzHTTP z error: )r   requestsr   ok
ValueErrorstatus_codetextr   )selfr   r   r   r   responses         b/var/www/html/test/engine/venv/lib/python3.12/site-packages/langchain_community/llms/databricks.pyr   z_DatabricksClientBase.request   si    "gdnn-=$>?##sG'
 {{uX%9%9$:(8==/RSS}}    c                 (    | j                  d|d       S )NGETr   )r%   r   s     r'   _getz_DatabricksClientBase._get&   s    ||E3--r(   c                 (    | j                  d||      S )NPOSTr+   )r%   r   r   s      r'   _postz_DatabricksClientBase._post)   s    ||FC11r(   Ntransform_output_fn.c                      y N )r%   r   r0   s      r'   postz_DatabricksClientBase.post,   s     r(   c                      y)NFr3   r%   s    r'   llmz_DatabricksClientBase.llm1   s    r(   r2   )__name__
__module____qualname____doc__str__annotations__r   r   r,   r/   r   r
   r   r4   propertyboolr7   r3   r(   r'   r   r      s    :LNc  c c . . .2 2s 2s 2 PT19(38:L1M	  T  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                     | 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                 x   t        |   di | 	 ddlm}  || j                        | _        | j
                  j                  | j                        }|j                  dd      j                         dv | _        | j                  |j                  d      | _        y y # t        $ r}t        d      |d }~ww xY w)	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,?,?@DK ;;++D,>,>?&.ll?B&G&M&M&O T
 '
# 99 V,DI   	C 	s   B 	B9(B44B9r   c                     | j                   dv S )N)llm/v1/chatllm/v1/completionsllama2/chat)rR   r6   s    r'   r7   z$_DatabricksServingEndpointClient.llma   s    yyPPPr(   beforemodevaluesc                 >    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   sC     F"&>D"?3M &9-UG 'F9r(   r   r0   .c                    | j                   rg| j                  j                  | j                  |      }|r ||      S | j                  dk(  rt        |      S | j                  dk(  rt        |      S |S d|gi}| j                  j                  | j                  |      }|d   }t        |t              r|d   n|}| j                  dk(  rt        |      S |r ||      S |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     &&;;&&0B0B7&SD"*400yyM)&t,,22-d33K  3WI>O{{**++O + H ]+E)%658EDyyM)-d330C&t,M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   s    D
IFC#(D(D(3--s -* QT Q Q (#c3h C   $ QUNN19(38:L1M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y
)#_DatabricksClusterDriverProxyClientzBAn API client that talks to a Databricks cluster driver proxy app.rM   
cluster_idcluster_driver_portrh   ri   rk   r   c                 L    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   sR     F"&>D-J/0D &<ZL$PG 'F9r(   Nr   r0   .c                 R    | j                  | j                  |      }|r ||      S |S r2   )r/   r   )r%   r   r0   rw   s       r'   r4   z(_DatabricksClusterDriverProxyClient.post   s+     zz$,,0,?"4(ITIr(   r2   )r8   r9   r:   r;   r<   r=   r   r{   r   r   ro   r
   r   r4   r3   r(   r'   r   r      s    L
IO(#c3h C   $ QUJJ19(38:L1MJ	Jr(   r   c                  N    	 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      s1    
A} 
P
 	

s    $c                     t        j                  d      } | s#	 t               j                  } | st	        d      	 | j                  d      j                  d      j                  d      } | S # t
        $ r}t	        d|       d}~ww xY w)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     99&'D	#%55D !KLL  ;;z")))4;;C@DK  	KKL#O 	s   !A, ,	B5BBc                      t        j                  d      x} r| S 	 t               j                  } | st	        d      	 | S # t
        $ r}t	        d|       d}~ww xY w)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~     II011y1
$&//	@AA    
HHIsL
 	

s   !? 	AAArS   c                 f    t        | t              sy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      s*    dC G$'((r(   allow_dangerous_deserializationc                     |st        d      	 ddl}	 |j                  t        j                  |             S # t        $ r}t        d|       d}~ww xY w# 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
  t!455	  KEaSIJJK
  
TUVTWX
 	

s,   8 #A 	AAA	A3 A..A3fnc                     	 ddl }	 |j                  |       j	                         S # t        $ r}t        d|       d}~ww xY w# 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      sx    K@  $((**	  KEaSIJJK
  @:1#>??@s)   & A 	A=A	A!AA!z0.3.3z1.0z#databricks_langchain.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                     | 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  sN      ++"
 99!YYF6N??&#'??F< r(   rh   ri   rk   c                     |j                  d      }|j                  d      }|r|rt        d      |rd |d<   n*|rn'	 t               j                  x}r||d<   t        d      |j                  d      }|r|rt        d      |rd |d<   n*|t        d      t        |      d	k  rt        d
|       	 |j                  d      x}rd|vsJ d       d|vsJ d       |S # t        $ r}t        d|       d }~ww xY w)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-LMM#'F< 	)9);)E)EE%E+=F<( !EFF %jj)>?=UVV,0F() (N  $%*<=P<QRSS!::n55<5</ </ - :- 9    c# s   &C! !	C=*C88C=rS   c                    d|v r0t        |d         r"t        |d   |j                  d            |d<   d|v r0t        |d         r"t        |d   |j                  d            |d<   t        |   d
i | | j
                  | j                  t        d      | j
                  t        j                  dt               | j                  rHt        | j                  | j                  | j                  | j                  | j                         | _        y | j$                  rI| j&                  r=t)        | j                  | j                  | j$                  | j&                        | _        y 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__  sc   4'N4@T;U,V)I./0451*D%& !D(^&'.
 +K/00451+D&' 	 4 (T->->-JMNN*MMN" ;YY.."00#22YYDL __!9!9>YY..??$($<$<	DL V r(   c                    | j                   | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  dnt        | j                        | j                  ddS 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     II!////#'#;#;"11 --++II// --II&&. #')$*A*AB''/ $(#
 	
& *$*B*BC'
 	
r(   c                     | j                   S r2   )r   r6   s    r'   _identifying_paramszDatabricks._identifying_params  s    ###r(   c                      y)zReturn type of llm.r   r3   r6   s    r'   	_llm_typezDatabricks._llm_type  s     r(   r   run_managerkwargsc                 x   d|i}| j                   j                  r|j                  | j                         |j                  | j                  xs | j
                         |j                  |       |r||d<   | j                  r | j                  di |}| j                   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""-d--88G||  d>V>V 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7D#7 +@AIsA $(M8C='
 !%J$ *.#-
 .2L(4S>*1
 .2*1
 9=(38"45< 'NC&FK#AsJ7 $D(49
$ $J$3#(#>L$sCx.>7D(3- -2#T1 &1]G"2L 	T#s(^ 	 	 (#*DcN *t *  $*X,s ,\ 
c3h 
 
0 $WS#X%6 $ $ 3   %):>	XX tCy!X 67	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      sT   	 	  # ? ?  * = .  .Is @*T#s(^ * *-T#s(^ - -8d38n 8 8FN'< FNRJ*? J2
# 
# (s &) ) )

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