o
    ưib                     @   s2  d dl Z d dlZd dlmZ d dlmZmZmZmZm	Z	m
Z
mZ d dlmZmZ d dlZd dlmZmZ d dlmZ d dlmZmZmZ d dlmZ d d	l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&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,m-Z- erd dl.m/Z0 e0Z1neZ1G dd deZ2G dd deZ3dS )    N)uuid)TYPE_CHECKINGAnyAsyncIteratorIteratorListOptionalUnion)HeadersResponse)verbose_loggerverbose_proxy_logger)get_str_from_messages)convert_to_ollama_imagecustom_prompt	ollama_pt)BaseModelResponseIterator)
BaseConfigBaseLLMExceptionget_secret_str)AllMessageValuesChatCompletionUsageBlock)DeltaGenericStreamingChunkModelInfoBaseModelResponseModelResponseStreamProviderFieldStreamingChoices   )OllamaError_convert_image)Loggingc                '       s  e Zd ZU dZ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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d< 																		dJdee dee	 dee	 dee dee dee d	ee d
ee dee	 dee	 dee dee dee	 dee dee dee	 dee dee ddf&ddZe fddZdee  fddZ!defddZ"de#d e#ded!e$de#f
d"d#Z%d$e#de$fd%d&Z&d$e#dee fd'd(Z'e(dee fd)d*Z)	dKded+ee de*fd,d-Z+d.ed/ed0e,e#e-f de.fd1d2Z/		dLded3e0d4e1d5e2d6e#d7ee3 d e#d8e#d9ed:ee d;ee$ de1fd<d=Z4ded7ee3 d e#d8e#d0e#de#fd>d?Z5		dLd0e#ded7ee3 d e#d8e#d:ee d+ee de#fd@dAZ6	dKd+ee d:ee ded e#d8e#dBee$ defdCdDZ7	EdMdFe,e8e e9e e1f dGe$d;ee$ fdHdIZ:  Z;S )NOllamaConfiga  
    Reference: https://github.com/ollama/ollama/blob/main/docs/api.md#parameters

    The class `OllamaConfig` provides the configuration for the Ollama's API interface. Below are the parameters:

    - `mirostat` (int): Enable Mirostat sampling for controlling perplexity. Default is 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0. Example usage: mirostat 0

    - `mirostat_eta` (float): Influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. Default: 0.1. Example usage: mirostat_eta 0.1

    - `mirostat_tau` (float): Controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. Default: 5.0. Example usage: mirostat_tau 5.0

    - `num_ctx` (int): Sets the size of the context window used to generate the next token. Default: 2048. Example usage: num_ctx 4096

    - `num_gqa` (int): The number of GQA groups in the transformer layer. Required for some models, for example it is 8 for llama2:70b. Example usage: num_gqa 1

    - `num_gpu` (int): The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. Example usage: num_gpu 0

    - `num_thread` (int): Sets the number of threads to use during computation. By default, Ollama will detect this for optimal performance. It is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Example usage: num_thread 8

    - `repeat_last_n` (int): Sets how far back for the model to look back to prevent repetition. Default: 64, 0 = disabled, -1 = num_ctx. Example usage: repeat_last_n 64

    - `repeat_penalty` (float): Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. Default: 1.1. Example usage: repeat_penalty 1.1

    - `temperature` (float): The temperature of the model. Increasing the temperature will make the model answer more creatively. Default: 0.8. Example usage: temperature 0.7

    - `seed` (int): Sets the random number seed to use for generation. Setting this to a specific number will make the model generate the same text for the same prompt. Example usage: seed 42

    - `stop` (string[]): Sets the stop sequences to use. Example usage: stop "AI assistant:"

    - `tfs_z` (float): Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. Default: 1. Example usage: tfs_z 1

    - `num_predict` (int): Maximum number of tokens to predict when generating text. Default: 128, -1 = infinite generation, -2 = fill context. Example usage: num_predict 42

    - `top_k` (int): Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. Default: 40. Example usage: top_k 40

    - `top_p` (float): Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. Default: 0.9. Example usage: top_p 0.9

    - `system` (string): system prompt for model (overrides what is defined in the Modelfile)

    - `template` (string): the full prompt or prompt template (overrides what is defined in the Modelfile)
    Nmirostatmirostat_etamirostat_taunum_ctxnum_gqanum_gpu
num_threadrepeat_last_nrepeat_penaltytemperatureseedstoptfs_znum_predicttop_ktop_psystemtemplatereturnc                 C   s>   t   }| D ]\}}|dkr|d urt| j|| q	d S )Nself)localscopyitemssetattr	__class__)r8   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   Zlocals_keyvalue r@   d/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/ollama/completion/transformation.py__init__j   s   
zOllamaConfig.__init__c                    s
   t   S N)super
get_config)clsr=   r@   rA   rE      s   
zOllamaConfig.get_configc                 C   s   t dddddgS )zDFor a given provider, return it's required fields with a descriptionbase_urlstringzYour Ollama API Basezhttp://10.10.11.249:11434)
field_nameZ
field_typeZfield_descriptionZfield_value)r   )r8   r@   r@   rA   get_required_params   s   z OllamaConfig.get_required_paramsmodelc                 C   s   g dS )N)

max_tokensstreamr4   r.   r/   frequency_penaltyr0   response_formatmax_completion_tokensreasoning_effortr@   )r8   rL   r@   r@   rA   get_supported_openai_params   s   z(OllamaConfig.get_supported_openai_paramsnon_default_paramsoptional_paramsdrop_paramsc                 C   s  |  D ]\}}|dks|dkr||d< q|dkr||d< q|dkr'||d< q|dkr0||d< q|dkr9||d< q|dkrB||d< q|d	krK||d	< q|d
krd|d urd|dr]||d< q|dv |d< q|dkrt|tr|d dkrxd|d< q|d dkr|d d |d< q|S )NrM   rQ   r2   rN   r.   r/   r4   rO   r0   rR   zgpt-ossthink>   highlowZmediumrP   typeZjson_objectjsonformatZjson_schemaZschema)r;   
startswith
isinstancedict)r8   rT   rU   rL   rV   paramr?   r@   r@   rA   map_openai_params   s4   









zOllamaConfig.map_openai_paramsollama_model_infoc                 C   s    t |ddpd}d| v S )zn
        Check if the 'template' field in the ollama_model_info contains a 'tools' or 'function' key.
        r6    Ztools)strgetlower)r8   rb   	_templater@   r@   rA   _supports_function_calling   s   z'OllamaConfig._supports_function_callingc                 C   s2   | di }| D ]\}}d|v r|  S q
d S )N
model_infoZcontext_length)re   r;   )r8   rb   Z_model_infokvr@   r@   rA   _get_max_tokens   s   zOllamaConfig._get_max_tokensc                  C   s<   ddl } ddl}ddlm} | jdp|jp|jp|dS )z?Get API key from environment variables or litellm configurationr   Nr   ZOLLAMA_API_KEY)oslitellmlitellm.secret_managers.mainr   environre   api_keyZ
openai_key)rm   rn   r   r@   r@   rA   get_api_key   s   zOllamaConfig.get_api_keyapi_basec           	      C   s   | ds
| dr|ddd }|ptdpd}|  }|r'dd| ini }ztjj| d	d
|i|d}W n& ty_ } zt	d||| t
|ddddddddW  Y d}~S d}~ww | }| |}t
|dd| |dd|||d	S )zc
        curl http://localhost:11434/api/show -d '{
          "name": "mistral"
        }'
        ollama/zollama_chat//   ZOLLAMA_API_BASEhttp://localhost:11434AuthorizationzBearer z	/api/showname)urlr[   headersz?OllamaError: Could not get model info for %s from %s. Error: %sZollamaZchatg        N)r>   litellm_providermodeinput_cost_per_tokenoutput_cost_per_tokenrM   max_input_tokensmax_output_tokens)	r>   r|   r}   Zsupports_function_callingr~   r   rM   r   r   )r]   splitr   rr   rn   Zmodule_level_clientpost	Exceptionr   debugr   r[   rl   rh   )	r8   rL   rs   rq   r{   responseeri   Z_max_tokensr@   r@   rA   get_model_info   s^   

zOllamaConfig.get_model_infoerror_messagestatus_coder{   c                 C   s   t |||dS )N)r   messager{   )r!   )r8   r   r   r{   r@   r@   rA   get_error_class  s   zOllamaConfig.get_error_classraw_responsemodel_responselogging_objrequest_datamessageslitellm_paramsencodingrq   	json_modec                 C   sD  ddl m} | }d|jd _|dddkr|dd}|r$| s7tjdd}||jd _	d|jd _nzUt
|}t|trvd	|v rvd
|v rv|}tjd dtt  |d	 t|d
 dddgd}||jd _	d|jd _ntjt|d}||jd _	d|jd _W nU tjy   d }d }|d ur||\}}tj||d}||jd _	d|jd _Y n+w |dd}d }d }|d urt|tr||\}}n|}||jd j	_||jd j	_tt |_d| |_|dd}|dt|	j|dd}|dt|dt dd}t|dtj|||| d |S )Nr   )_parse_content_for_reasoningr0   r\   rc   r[   r   )contentry   	argumentsZcall_)ry   r   function)idr   rZ   )r   
tool_callsr   )r   reasoning_contentrt   promptprompt_eval_countr@   )Zdisallowed_special
eval_countr   r   usageprompt_tokenscompletion_tokensZtotal_tokens)8litellm.litellm_core_utils.prompt_templates.common_utilsr   r[   choicesfinish_reasonre   striprn   Messager   loadsr^   r_   rd   r   uuid4dumpsJSONDecodeErrorr   r   inttimecreatedrL   lenencoder<   Usage)r8   rL   r   r   r   r   r   rU   r   r   rq   r   r   Zresponse_jsonZresponse_textr   Zresponse_contentZfunction_callr   r   Z_promptr   r   r@   r@   rA   transform_response#  s   

	zOllamaConfig.transform_responsec                 C   s
  | dptj}| d}||v r$|| }t|d |d |d |d}	n#|r,t|d}	nt||d}
t|
trE|
d	 |
d
 }	}||d
< n|
}	|dd}|dd }|d
d }|dd }||	||d}|d urn||d< |d ur{dd |D |d
< |d ur||d< |S )Ncustom_prompt_dictZtext_completionZrolesinitial_prompt_valuefinal_prompt_value)Z	role_dictr   r   r   )r   )rL   r   r   imagesrN   Fr\   rW   )rL   r   optionsrN   c                 S   s   g | ]}t t|qS r@   )r"   r   ).0imager@   r@   rA   
<listcomp>  s    z2OllamaConfig.transform_request.<locals>.<listcomp>)	re   rn   r   r   r   r   r^   r_   pop)r8   rL   r   rU   r   r{   r   Ztext_completion_requestZmodel_prompt_detailsZollama_promptZmodified_promptr   rN   r\   rW   datar@   r@   rA   transform_request  sL   	



zOllamaConfig.transform_requestc                 C   s   |S rC   r@   )r8   r{   rL   r   rU   r   rq   rs   r@   r@   rA   validate_environment  s   
z!OllamaConfig.validate_environmentrN   c                 C   s,   |du rd}| dr|}|S | d}|S )z{
        OPTIONAL

        Get the complete url for the request

        Some providers need `model` in `api_base`
        Nrw   z/api/generate)endswith)r8   rs   rq   rL   rU   r   rN   rz   r@   r@   rA   get_complete_url  s   

zOllamaConfig.get_complete_urlFstreaming_responsesync_streamc                 C   s   t |||dS )N)r   r   r   )$OllamaTextCompletionResponseIteratorr8   r   r   r   r@   r@   rA   get_model_response_iterator  s
   z(OllamaConfig.get_model_response_iterator)NNNNNNNNNNNNNNNNNNrC   )NNF)<__name__
__module____qualname____doc__r%   r   r   __annotations__r&   floatr'   r(   r)   r*   r+   r,   r-   r.   r/   r0   listr1   r2   r3   r4   r5   rd   r6   rB   classmethodrE   r   r   rK   rS   r_   boolra   rh   rl   staticmethodrr   r   r   r	   r
   r   r   r   r   LiteLLMLoggingObjr   r   r   r   r   r   r   r   __classcell__r@   r@   rG   rA   r$   *   s  
 *	


#
:

	

n
?	

r$   c                       sb   e Zd Z	ddedee f fddZdedeee	f fdd	Z
d
edeee	f fddZ  ZS )r   Fr   r   c                    s    t  ||| d| _d| _d S )NF)rD   rB   started_reasoning_contentfinished_reasoning_contentr   rG   r@   rA   rB     s   
z-OllamaTextCompletionResponseIterator.__init__str_liner7   c                 C   s   |  t|S rC   )chunk_parserr[   r   )r8   r   r@   r@   rA   _handle_string_chunk  s   z9OllamaTextCompletionResponseIterator._handle_string_chunkchunkc              
   C   s  zd|v rt d| d}d}d }|d du rFd}d}d}|dd }|d	d }d }|d ur=|d ur=t|||| d
}t||||dW S |d r|d }d }d }	|d ur|d|v rd|dd}d| _nd|v rq|dd}d| _| jrz| jsz|}n|}	ttdt	||	ddg|d dW S d|v r|d s|dpd}
ttdt	|
ddgdW S ttdt	dddgdW S  t y } z
t
d|  |d }~ww )NerrorzOllama Error - rc   FdoneTr0   r   r   r   )textis_finishedr   r   r   z<think>z</think>r   )r   r   )indexdelta)r   r   r   Zthinking)r   )r   zUnable to parse ollama chunk - )r   re   r   r   replacer   r   r   r   r   r   r   )r8   r   r   r   r   r   r   r   r   r   Zthinking_contentr   r@   r@   rA   r     s   	z1OllamaTextCompletionResponseIterator.chunk_parserr   )r   r   r   r   r   rB   rd   r	   r   r   r   r_   r   r   r@   r@   rG   rA   r     s"    


r   )4r[   r   Zlitellm._uuidr   typingr   r   r   r   r   r   r	   Zhttpx._modelsr
   r   rn   Zlitellm._loggingr   r   r   r   Z3litellm.litellm_core_utils.prompt_templates.factoryr   r   r   Z)litellm.llms.base_llm.base_model_iteratorr   Z)litellm.llms.base_llm.chat.transformationr   r   ro   r   Zlitellm.types.llms.openair   r   Zlitellm.types.utilsr   r   r   r   r   r   r   Zcommon_utilsr!   r"   Z*litellm.litellm_core_utils.litellm_loggingr#   Z_LiteLLMLoggingObjr   r$   r   r@   r@   r@   rA   <module>   s0    $$
   T