
    dhfQ                        S SK r S SKrS SKrS SKJrJr  S SKJrJrJ	r	J
r
JrJr  S SKrS SKJr  S SKJr  S SKJr  S SKJrJrJrJrJr  S/r " S	 S
\\5      rS\	\\4   S\4S jrS\	\\4   S\4S jrS\	\\4   S\4S jr " S S\5      r  " S S\5      r!S\4S jr"S\4S jr#S\4S jr$S\S\%4S jr&S\S\\%   S\4S jr'S\S\4S jr(\" SSSS 9 " S! S\5      5       r)g)"    N)ABCabstractmethod)AnyCallableDictListMappingOptional)
deprecated)CallbackManagerForLLMRun)LLM)	BaseModel
ConfigDictFieldPrivateAttrmodel_validator
Databricksc            	           \ rS rSr% Sr\\S'   \\S'   S\S\S\S\4S	 jrS\S\4S
 jr	S\S\S\4S jr
\ SS\S\\S\4      S\4S jj5       r\S\4S j5       rSrg)_DatabricksClientBase   z0A base JSON API client that talks to Databricks.api_url	api_tokenmethodurlrequestreturnc                     SSU R                    30n[        R                  " XXCS9nUR                  (       d%  [	        SUR
                   SUR                   35      eUR                  5       $ )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/shao/venv/lib/python3.13/site-packages/langchain_community/llms/databricks.pyr   _DatabricksClientBase.request   se    "gdnn-=$>?##G
 {{uX%9%9$:(8==/RSS}}    c                 (    U R                  SUS 5      $ )NGETr   )r&   r   s     r(   _get_DatabricksClientBase._get&   s    ||E3--r*   c                 &    U R                  SX5      $ )NPOSTr-   )r&   r   r   s      r(   _post_DatabricksClientBase._post)   s    ||FC11r*   Ntransform_output_fn.c                     g N )r&   r   r4   s      r(   post_DatabricksClientBase.post,   s     r*   c                     g)NFr7   r&   s    r(   llm_DatabricksClientBase.llm1   s    r*   r7   r6   )__name__
__module____qualname____firstlineno____doc__str__annotations__r   r   r.   r2   r   r
   r   r8   propertyboolr<   __static_attributes__r7   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                     U S   S   S   $ )Nchoicesr   r%   r7   r'   s    r(   _transform_completionsrK   6   s    Iq!&))r*   c                     U S   S   S   $ )N
candidatesr   r%   r7   rJ   s    r(   _transform_llama2_chatrN   :   s    L!!$V,,r*   c                     U S   S   S   S   $ )NrI   r   messagecontentr7   rJ   s    r(   _transform_chatrR   >   s    Iq!),Y77r*   c                      ^  \ rS rSr% Sr\\S'   \\S'   \\S'   Sr\\S'   Sr	\
\S	'   Sr\\   \S
'   S\4U 4S jjr\S\
4S j5       r\" SS9\S\\\4   S\4S j5       5       r SS\S\\S\4      S\4S jjrSrU =r$ ) _DatabricksServingEndpointClientB   z:An API client that talks to a Databricks serving endpoint.hostendpoint_namedatabricks_uriNclientFexternal_or_foundationtaskdatac                   > [         TU ]  " S0 UD6   SSKJn  U" U R                  5      U l        U R
                  R                  U R                  5      nUR                  SS5      R                  5       S;   U l        U R                  c  UR                  S5      U l        g g ! [         a  n[        S5      UeS nAff = f)	Nr   )get_deploy_clientzMFailed to create the client. Please install mlflow with `pip install mlflow`.endpoint_type )external_modelfoundation_model_apir[   r7   )super__init__mlflow.deploymentsr^   rX   rY   ImportErrorget_endpointrW   getlowerrZ   r[   )r&   r\   r^   eendpoint	__class__s        r(   rd   )_DatabricksServingEndpointClient.__init__L   s     4 	<+D,?,?@DK ;;++D,>,>?&.ll?B&G&M&M&O T
 '
# 99 V,DI   	C 	s   B" "
B=,B88B=r   c                      U R                   S;   $ )N)llm/v1/chatllm/v1/completionsllama2/chat)r[   r;   s    r(   r<   $_DatabricksServingEndpointClient.llma   s    yyPPPr*   beforemodevaluesc                 @    SU;  a  US   nUS   nSU SU S3nXAS'   U$ )Nr   rV   rW   https://z/serving-endpoints/z/invocationsr7   )clsrv   rV   rW   r   s        r(   set_api_url,_DatabricksServingEndpointClient.set_api_urle   sA     F"&>D"?3M &9-UG '9r*   r   r4   .c                    U R                   (       ak  U R                  R                  U R                  US9nU(       a  U" U5      $ U R                  S:X  a  [        U5      $ U R                  S:X  a  [        U5      $ U$ SU/0nU R                  R                  U R                  US9nUS   n[        U[        5      (       a  US   OUnU R                  S:X  a  [        U5      $ U(       a  U" U5      $ U$ )N)rk   inputsro   rp   dataframe_recordspredictionsr   rq   )
rZ   rY   predictrW   r[   rR   rK   
isinstancelistrN   )r&   r   r4   respwrapped_requestr'   predspreds           r(   r8   %_DatabricksServingEndpointClient.posto   s     &&;;&&0B0B7&SD"*400yyM)&t,,22-d33K  3WI>O{{**++O + H ]+E)%6658EDyyM)-d330C&t,MMr*   )rY   rZ   r[   r6   )r>   r?   r@   rA   rB   rC   rD   rY   r   rZ   rF   r[   r
   rd   rE   r<   r   classmethodr   rz   r   r8   rG   __classcell__rl   s   @r(   rT   rT   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 Nr*   rT   c                       \ rS rSr% Sr\\S'   \\S'   \\S'   \" SS9\S\	\\
4   S	\
4S
 j5       5       r SS\
S\\S\4      S	\
4S jjrSrg)#_DatabricksClusterDriverProxyClient   zBAn API client that talks to a Databricks cluster driver proxy app.rV   
cluster_idcluster_driver_portrs   rt   rv   r   c                 N    SU;  a  US   nUS   nUS   nSU SU SU 3nXQS'   U$ )Nr   rV   r   r   rx   z/driver-proxy-api/o/0//r7   )ry   rv   rV   r   portr   s         r(   rz   /_DatabricksClusterDriverProxyClient.set_api_url   sP     F"&>D-J/0D &<ZL$PG '9r*   Nr   r4   .c                 \    U R                  U R                  U5      nU(       a  U" U5      $ U$ r6   )r2   r   )r&   r   r4   r   s       r(   r8   (_DatabricksClusterDriverProxyClient.post   s+     zz$,,0,?"4(ITIr*   r7   r6   )r>   r?   r@   rA   rB   rC   rD   r   r   r   r   rz   r
   r   r8   rG   r7   r*   r(   r   r      s    L
IO(#c3h C   $ QUJJ19(38:L1MJ	J Jr*   r   c                  P     SSK Jn   U " 5       $ ! [         a    [        S5      ef = f)z_Get 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   rf   r   s    r(   get_repl_contextr      s1    
A} 
P
 	

s    %c                  .   [         R                  " S5      n U (       d(   [        5       R                  n U (       d  [	        S5      e U R                  S5      R                  S5      R                  S5      n U $ ! [
         a  n[	        SU 35      eSnAff = f)zsGet 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: Nrx   zhttp://r   )osgetenvr   browserHostNamer#   	Exceptionlstriprstrip)rV   rj   s     r(   get_default_hostr      s     99&'D	#%55D !KLL  ;;z")))4;;C@DK  	KKL#O 	s   &A7 7
BBBc                      [         R                  " S5      =n (       a  U $  [        5       R                  n U (       d  [	        S5      e U $ ! [
         a  n[	        SU 35      eSnAff = f)zsGet 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   rj   s     r(   get_default_api_tokenr      s~     II011y1
$&//	@AA    
HHIsL
 	

s   &A
 

A'A""A'r\   c                 p    [        U [        5      (       d  gSn[        [        R                  " X5      5      $ )zJChecks if a data is a valid hexadecimal string using a regular expression.Fz^[0-9a-fA-F]+$)r   rC   rF   rematch)r\   patterns     r(   _is_hex_stringr      s+    dC  G'((r*   allow_dangerous_deserializationc                     U(       d  [        S5      e SSKn UR                  [        R                  U 5      5      $ ! [         a  n[        SU 35      eSnAff = f! [         a  n[        SU 35      eSnAff = f)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)r\   r   r   rj   s       r(    _load_pickled_fn_from_hex_stringr      s     +A
 	
K
  t!455	  KEaSIJJK
  
TUVTWX
 	

s,   = #A 
AAA
A:'A55A:fnc                      SSK n UR                  U 5      R	                  5       $ ! [         a  n[        SU 35      eSnAff = f! [         a  n[        SU 35      eSnAff = f)z6Pickles a function and returns the hexadecimal string.r   Nr   zFailed to pickle the function: )r   r   r#   dumpshex)r   r   rj   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                     ^  \ rS rSr% Sr\" \S9r\\	S'    \" \
S9r\\	S'    Sr\\   \	S'    Sr\\   \	S'    Sr\\   \	S	'    Sr\\\\4      \	S
'    Sr\\   \	S'    Sr\\S\4      \	S'    Sr\\	S'    Sr\\	S'    Sr\\	S'    Sr\\\      \	S'    Sr\\   \	S'    \" \S9r\\\4   \	S'    Sr \\   \	S'    Sr!\"\	S'    \#" 5       r$\%\	S'   \&" SS9r'\(S\\\4   4S j5       r)\*" SS 9\+S!\\\4   S\4S" j5       5       r,S#\4U 4S$ jjr-\(S\\\4   4S% j5       r.\(S\/\\4   4S& j5       r0\(S\4S' j5       r1  S-S(\S\\\      S)\\2   S*\S\4
S+ jjr3S,r4U =r5$ ).r   i
  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_factoryrV   r   NrW   r   r   model_kwargstransform_input_fn.r4   
databricksrX   g        temperature   nstop
max_tokensextra_paramsr[   Fr   _clientforbid)extrar   c                     U R                   U R                  S.nU R                  (       a  U R                  US'   U R                  b  U R                  US'   U$ )N)r   r   r   r   )r   r   r   r   )r&   paramss     r(   _llm_paramsDatabricks._llm_params  sN      ++"
 99!YYF6N??&#'??F< r*   rs   rt   rv   c                 f   UR                  S5      nUR                  S5      nU(       a  U(       a  [        S5      eU(       a  S US'   O3U(       a  O+ [        5       R                  =n(       a  XAS'   [        S5      eUR                  S5      nU(       a  U(       a  [        S5      eU(       a  S US'   O,Uc  [        S5      e[        U5      S	::  a  [        S
U 35      e UR                  S5      =n(       a  SU;  d   S5       eSU;  d   S5       eU$ ! [         a  n[        SU 35      eS nAff = f)Nr   rW   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')rh   r#   r   	clusterIdr   int)ry   rv   r   rW   context_cluster_idrj   r   r   s           r(   set_cluster_idDatabricks.set_cluster_id  s\    ZZ-


?3-LMM#'F< 	)9);)E)EE%E+=<( !EFF %jj)>?=UVV,0F() (N  $%*<=P<QRSS!::n55<5</ </ - :- 9    c# s   *D 
D0D++D0r\   c                   > SU;   a2  [        US   5      (       a  [        US   UR                  S5      S9US'   SU;   a2  [        US   5      (       a  [        US   UR                  S5      S9US'   [        TU ]  " S
0 UD6  U R
                  b  U R                  b  [        S5      eU R
                  b  [        R                  " S[        5        U R                  (       aE  [        U R                  U R                  U R                  U R                  U R                   S9U l        g U R$                  (       aK  U R&                  (       a:  [)        U R                  U R                  U R$                  U R&                  S9U l        g [        S	5      e)Nr   r   )r\   r   r4   z.Cannot set both extra_params and extra_params.z<model_kwargs is deprecated. Please use extra_params instead.)rV   r   rW   rX   r[   )rV   r   r   r   zDMust specify either endpoint_name or cluster_id/cluster_driver_port.r7   )r   r   rh   rc   rd   r   r   r#   warningswarnDeprecationWarningrW   rT   rV   r   rX   r[   r   r   r   r   )r&   r\   rl   s     r(   rd   Databricks.__init__  sk   4'N4@T;U,V,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                    U R                   U R                  U R                  U R                  U R                  U R
                  U R                  U R                  U R                  U R                  U R                  U R                  U R                  c  SO[        U R                  5      U R                  c  SS.$ [        U R                  5      S.$ )zReturn default params.N)rV   rW   r   r   rX   r   r   r   r   r   r   r[   r   r4   )rV   rW   r   r   rX   r   r   r   r   r   r   r[   r   r   r4   r;   s    r(   _default_paramsDatabricks._default_params  s     II!////#'#;#;"11 --++II// --II&&. #')$*A*AB''/ $(#
 	
& *$*B*BC'
 	
r*   c                     U R                   $ r6   )r   r;   s    r(   _identifying_paramsDatabricks._identifying_params  s    ###r*   c                     g)zReturn type of llm.r   r7   r;   s    r(   	_llm_typeDatabricks._llm_type  s     r*   r   run_managerkwargsc                    SU0nU R                   R                  (       a  UR                  U R                  5        UR                  U R                  =(       d    U R
                  5        UR                  U5        U(       a  X%S'   U R                  (       a  U R                  " S0 UD6nU R                   R                  XPR                  S9$ )zAQueries the LLM endpoint with the given prompt and stop sequence.r   r   )r4   r7   )	r   r<   updater   r   r   r   r8   r4   )r&   r   r   r   r   r   s         r(   _callDatabricks._call$  s     $,V"4<<NN4++,t((=D,=,=>v"FO""--88G||  >V>V WWr*   )r   )NN)6r>   r?   r@   rA   rB   r   r   rV   rC   rD   r   r   rW   r
   r   r   r   r   r   r   r   r4   rX   r   floatr   r   r   r   r   dictr   r[   r   rF   r   r   r   r   model_configrE   r   r   r   r   rd   r   r	   r   r   r   r   rG   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 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   rC   rK   rN   rR   rT   r   r   r   r   rF   r   r   r   r   r7   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*   