
    7|h:                         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	 d dl
mZ d dlmZ d dlmZ d dlmZmZmZ d dlmZmZmZ d dlmZmZ  e j6                  e      Z ed	d
d       G d de             Zy)    N)AnyDictIteratorListMappingOptionalUnion)
deprecated)CallbackManagerForLLMRun)BaseLLM)
GenerationGenerationChunk	LLMResult)convert_to_secret_strget_from_dict_or_envpre_init)
ConfigDict	SecretStrz0.0.18z1.0zlangchain_ibm.WatsonxLLM)sinceremovalalternative_importc                      e Zd ZU dZdZeed<   	 dZeed<   	 dZeed<   	 d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d<   	 dZe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f   ed<   	 dZeed<   	 dZeed<    ed      Zedefd       Zede eef   fd       Z!e"de de fd       Z#ede$eef   fd       Z%edefd       Z&e'	 d,dee(e eef         de eef   fd       Z)d,dee(e      de eef   fd Z*de(e   de+fd!Z,d"e eef   de-fd#Z.	 	 d-d$edee(e      d%ee/   d&edef
d'Z0	 	 	 d.d(e(e   dee(e      d%ee/   d)ee   d&ede+fd*Z1	 	 d-d$edee(e      d%ee/   d&ede2e-   f
d+Z3y)/
WatsonxLLMa-  
    IBM watsonx.ai large language models.

    To use, you should have ``ibm_watsonx_ai`` python package installed,
    and the environment variable ``WATSONX_APIKEY`` set with your API key, or pass
    it as a named parameter to the constructor.


    Example:
        .. code-block:: python

            from ibm_watsonx_ai.metanames import GenTextParamsMetaNames
            parameters = {
                GenTextParamsMetaNames.DECODING_METHOD: "sample",
                GenTextParamsMetaNames.MAX_NEW_TOKENS: 100,
                GenTextParamsMetaNames.MIN_NEW_TOKENS: 1,
                GenTextParamsMetaNames.TEMPERATURE: 0.5,
                GenTextParamsMetaNames.TOP_K: 50,
                GenTextParamsMetaNames.TOP_P: 1,
            }

            from langchain_community.llms import WatsonxLLM
            watsonx_llm = WatsonxLLM(
                model_id="google/flan-ul2",
                url="https://us-south.ml.cloud.ibm.com",
                apikey="*****",
                project_id="*****",
                params=parameters,
            )
     model_iddeployment_id
project_idspace_idNurlapikeytokenpasswordusernameinstance_idversionparamsverifyF	streamingwatsonx_modelforbid)extrareturnc                      y)NF )clss    b/var/www/html/test/engine/venv/lib/python3.12/site-packages/langchain_community/llms/watsonxllm.pyis_lc_serializablezWatsonxLLM.is_lc_serializablef   s        c                     dddddddS )NWATSONX_URLWATSONX_APIKEYWATSONX_TOKENWATSONX_PASSWORDWATSONX_USERNAMEWATSONX_INSTANCE_ID)r   r    r!   r"   r#   r$   r.   selfs    r0   
lc_secretszWatsonxLLM.lc_secretsj   s      !&$**0
 	
r2   valuesc           
         t        t        |dd            |d<   d|j                  dd      j                         v rt        t        |dd            |d<   nD|d   sKdt        j
                  vr9|d	   s4d
t        j
                  vr"|d   sdt        j
                  vrt        d      |d   sdt        j
                  v rt        t        |dd            |d<   n|d	   sd
t        j
                  v r3t        t        |d	d
            |d	<   t        t        |dd            |d<   nI|d   sdt        j
                  v r2t        t        |dd            |d<   t        t        |dd            |d<   |d   rdt        j
                  vrt        t        |dd            |d<   	 ddlm} |d   r|d   j                         nd|d   r|d   j                         nd|d   r|d   j                         nd|d	   r|d	   j                         nd|d   r|d   j                         nd|d   r|d   j                         nd|d   r|d   j                         ndd}|j                         D ci c]  \  }}|	|| }}} ||d   |d   ||d   |d   |d   |d         }||d<   |S c c}}w # t        $ r t        d      w xY w)zCValidate that credentials and python package exists in environment.r   r4   zcloud.ibm.comr   r    r5   r!   r6   r"   r7   zDid not find 'token', 'password' or 'apikey', please add an environment variable `WATSONX_TOKEN`, 'WATSONX_PASSWORD' or 'WATSONX_APIKEY' which contains it, or pass 'token', 'password' or 'apikey' as a named parameter.r#   r8   r$   r9   r   )ModelInferenceNr%   )r   r    r!   r"   r#   r$   r%   r   r   r&   r   r   r'   )r   r   credentialsr&   r   r   r'   r)   zdCould not import ibm_watsonx_ai python package. Please install it with `pip install ibm_watsonx_ai`.)r   r   getget_secret_valueosenviron
ValueError ibm_watsonx_ai.foundation_modelsr?   itemsImportError)r/   r=   r?   r@   keyvaluecredentials_without_none_valuer)   s           r0   validate_environmentzWatsonxLLM.validate_environmentu   s3    . >
u fjj3DDFF4$VX7GH F8
 7O#2::5z*&bjj8x($BJJ6 -  Orzz$A"7(/J#w 
#'9RZZ'G%:(=OP&z" &;(=OP&z" !%5%C#8(;KL$x  &;(=OP&z" -(,A,S(=(@UV)}%1	G <B%=ve}557d;A(;KF8$557QU ;A/F7O446t j) :&779 j) :&779 m, =)::< =C9<MF9%668SW1K8 .9->->-@.)sEEDUU
.* . +
+$_5:h'!,/
+h'M '4F?# ).  	G 	s%   CJ( '
J"2J"7)J( "J( (J=c                 v    | j                   | j                  | j                  | j                  | j                  dS )zGet the identifying parameters.r   r   r&   r   r   rN   r:   s    r0   _identifying_paramszWatsonxLLM._identifying_params   s3     !//kk//
 	
r2   c                      y)zReturn type of llm.zIBM watsonx.air.   r:   s    r0   	_llm_typezWatsonxLLM._llm_type   s      r2   responsec                     | dddS d}d}dt         dt        t         t        f   dt        fd}| D ]4  }|j	                  d      }|s| |d|d         z  }| |d	|d         z  }6 ||dS )
Nr   )generated_token_countinput_token_countrI   resultr,   c                 .    |j                  | d      xs dS )Nr   )rA   )rI   rV   s     r0   get_count_valuez8WatsonxLLM._extract_token_usage.<locals>.get_count_value   s    ::c1%**r2   resultsrU   rT   )strr   r   intrA   )rR   rU   rT   rX   resrY   s         r0   _extract_token_usagezWatsonxLLM._extract_token_usage   s     -.QGG !	+ 	+d38n 	+ 	+  	Cggi(G!_5H'RS*%UU!%+WQZ* %		 &;!2
 	
r2   stopc                 L    | j                   ri | j                   ni }|||d<   |S )Nstop_sequences)r&   )r;   r^   r&   s      r0   _get_chat_paramszWatsonxLLM._get_chat_params  s-    48KKDKKR'+F#$r2   c                 :   g }|D ]]  }|j                  d      }|s|d   j                  d      }t        |d   j                  d      d|i      }|j                  |g       _ | j                  |      }|| j                  | j
                  d}t        ||      S )	z2Create the LLMResult from the choices and prompts.rY   r   stop_reasongenerated_textfinish_reasontextgeneration_info)token_usager   r   generations
llm_output)rA   r   appendr]   r   r   r   )	r;   rR   rk   r\   rY   re   genfinal_token_usagerl   s	            r0   _create_llm_resultzWatsonxLLM._create_llm_result  s     	*Cggi(G '
} =  (89%4m$D ""C5)	* !55h?,!//


 [ZHHr2   stream_responsec           	          |d   st        d      S t        |d   d   d   t        |d   d   j                  dd      | j                  | j                  d	      
      S )z0Convert a stream response to a generation chunk.rY   r   rg   r   rd   rc   N)r   r   )re   rl   rf   )r   dictrA   r   r   )r;   rq   s     r0   $_stream_response_to_generation_chunkz/WatsonxLLM._stream_response_to_generation_chunk  sn    
 y)"++ +A./?@ -i8;??tT $%)%7%7	
 		
r2   promptrun_managerkwargsc                 h     | j                   d|g||d|}|j                  d   d   j                  S )a  Call the IBM watsonx.ai inference endpoint.
        Args:
            prompt: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.
            run_manager: Optional callback manager.
        Returns:
            The string generated by the model.
        Example:
            .. code-block:: python

                response = watsonx_llm.invoke("What is a molecule")
        )promptsr^   rw   r   r.   )	_generaterk   rg   )r;   rv   r^   rw   rx   rV   s         r0   _callzWatsonxLLM._call1  sH    &   
H4[
DJ
 !!!$Q',,,r2   rz   streamc                    | j                  |      }||n| j                  }|rt        |      dkD  rt        d|       t	        d      } | j
                  |d   f||d|}	|	D ]  }
||
}||
z  } |J t        |j                  t              r*|j                  j                  d      }t        |gg|	      S t        |gg
      S | j                  j                  ||      }| j                  |      S )a  Call the IBM watsonx.ai inference endpoint which then generate the response.
        Args:
            prompts: List of strings (prompts) to pass into the model.
            stop: Optional list of stop words to use when generating.
            run_manager: Optional callback manager.
        Returns:
            The full LLMResult output.
        Example:
            .. code-block:: python

                response = watsonx_llm.generate(["What is a molecule"])
        r^      z6WatsonxLLM currently only supports single prompt, got r   rs   r   )r^   rw   rl   rj   )rk   )rv   r&   )ra   r(   lenrE   r   _stream
isinstancerh   rt   popr   r)   generaterp   )r;   rz   r^   rw   r}   rx   r&   should_stream
generationstream_iterchunkrl   rR   s                r0   r{   zWatsonxLLM._generateI  s(   ( &&D&1"("4$..7|a LWIV  )b1J&$,,
!%;BHK % (%!&J%'J	(
 )))*44d;'77;;LI
 zl^
SS:,88))22'&2QH**844r2   c              +      K   | j                  |      }| j                  j                  |d|      D ]6  }| j                  |      }|r|j	                  |j
                  |       | 8 yw)a4  Call the IBM watsonx.ai inference endpoint which then streams the response.
        Args:
            prompt: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.
            run_manager: Optional callback manager.
        Returns:
            The iterator which yields generation chunks.
        Example:
            .. code-block:: python

                response = watsonx_llm.stream("What is a molecule")
                for chunk in response:
                    print(chunk, end='')  # noqa: T201
        r   T)rv   raw_responser&   )r   N)ra   r)   generate_text_streamru   on_llm_new_tokenrg   )r;   rv   r^   rw   rx   r&   stream_respr   s           r0   r   zWatsonxLLM._streamv  sy     * &&D&1--BBV C 
 	K ==kJE,,UZZu,EK	s   A+A-)N)NN)NNN)4__name__
__module____qualname____doc__r   rZ   __annotations__r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   rt   r'   r	   boolr(   r)   r   r   model_configclassmethodr1   propertyr   r<   r   rL   r   rO   rQ   staticmethodr   r]   ra   r   rp   r   ru   r   r|   r{   r   r   r.   r2   r0   r   r      sK   > HcM3(J*Hc(#C)	#1"&FHY&4!%E8I%3$(Hhy!(6$(Hhy!(6'+K)$+9#'GXi '5!FHTN!;!FE#t)!0 It1M3L 4   
DcN 
 
 c$ c4 c cJ 
WS#X%6 
 
  3     37
4S#X/0
	c3h
 
2Xd3i%8 DcN I4: I) I(
c3h
 

* %):>	-- tCy!- 67	-
 - 
-6 %):>!%+5c+5 tCy!+5 67	+5
 +5 +5 
+5` %):>	 tCy! 67	
  
/	"r2   r   )loggingrC   typingr   r   r   r   r   r   r	   langchain_core._api.deprecationr
   langchain_core.callbacksr   #langchain_core.language_models.llmsr   langchain_core.outputsr   r   r   langchain_core.utilsr   r   r   pydanticr   r   	getLoggerr   loggerr   r.   r2   r0   <module>r      si     	 F F F 6 = 7 I I V V *			8	$ 
E6PA AAr2   