
    hCO                     
   d dl Z 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
mZ d dlmZmZ d dlmZ d dlZd dlmZ d dlmZmZ d dlmZmZ d dlmZmZmZ d d	lmZm Z  d
dl!m"Z" er	d dl#m$Z% e%Z&neZ& G d de      Z' G d de      Z(y)    N)TYPE_CHECKINGAnyAsyncIteratorIteratorListOptionalUnioncast)HeadersResponse)	BaseModel)BaseModelResponseIterator)
BaseConfigBaseLLMException)OllamaToolCallOllamaToolCallFunction)AllMessageValuesChatCompletionAssistantToolCallChatCompletionUsageBlock)ModelResponseModelResponseStream   OllamaError)Loggingc            %           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<   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d3d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Ze fd       ZdefdZdededededef
dZ	 	 d4dededee    deded ee   d!ee   defd"Z!	 d5d!ee   d ee   dededed#ee   defd$Z"dedee    dedededefd%Z#	 	 d4ded&e$d'e%d(e&d)edee    deded*ed ee   d+ee   de%fd,Z'd-ed.ede(ee)f   de*fd/Z+	 d6d0e(e,e   e-e   e%f   d1ed+ee   fd2Z. xZ/S )7OllamaChatConfiga  
    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_threadrepeat_last_nrepeat_penaltyseedtfs_znum_predicttop_ksystemtemplatetemperaturestoptop_preturnc                     t               j                         }|j                         D ]%  \  }}|dk7  s|t        | j                  ||       ' y )Nself)localscopyitemssetattr	__class__)r1   r   r   r    r!   r"   r#   r$   r%   r,   r&   r-   r'   r(   r)   r.   r*   r+   locals_keyvalues                        c/var/www/Befach/backend/env/lib/python3.12/site-packages/litellm/llms/ollama/chat/transformation.py__init__zOllamaChatConfig.__init__a   sA    ( (--/!--/JCf}!2U3 *    c                      t         |          S N)super
get_config)clsr6   s    r:   r@   zOllamaChatConfig.get_configz   s    w!##r<   modelc                 
    g dS )N)
max_tokensmax_completion_tokensstreamr.   r,   r&   frequency_penaltyr-   toolstool_choice	functionsresponse_format )r1   rB   s     r:   get_supported_openai_paramsz,OllamaChatConfig.get_supported_openai_params~   s    
 	
r<   non_default_paramsoptional_paramsdrop_paramsc                    |j                         D ]S  \  }}|dk(  s|dk(  r||d<   |dk(  r||d<   |dk(  r||d<   |dk(  r||d<   |dk(  r||d<   |dk(  r||d	<   |d
k(  r||d
<   |dk(  r)t        |t              r|j                  d      dk(  rd|d<   |dk(  rTt        |t              rD|j                  d      dk(  r0|j                  d      r|d   j                  d      r|d   d   |d<   |dk(  r8	 t	        j
                  |d      }|j                  d      du r||d<   nt        	 |dk(  s	 t	        j
                  |d      }|j                  d      du r||d<   nt        V |j                  dd        |j                  dd        |S # t        $ r: d|d<   dt        _        ||d<   t        |d         dk(  r|d   d   d   d   |d<   Y w xY w# t        $ r( d|d<   dt        _        |j                  d      |d<   Y w xY w)NrD   rE   r(   rF   r,   r&   r.   rG   r%   r-   rK   typejson_objectjsonformatjson_schemaschemarH   ollama)rB   custom_llm_providersupports_function_callingTfunctions_unsupported_model   r   functionnamefunction_namerJ   rI   )
r4   
isinstancedictgetlitellmget_model_info	Exceptionadd_function_to_promptlenpop)r1   rN   rO   rB   rP   paramr9   
model_infos           r:   map_openai_paramsz"OllamaChatConfig.map_openai_params   s    /446LE5$1H(H16. ,1)%16.*/'+0(++49 01*/'**ud+IIf%6,2)**ud+IIf%699]+m0D0H0H0R05m0DX0NOH-1!(!7!7#"J "~~&ABdJ380' 1 #<!(!7!7#"J "~~&ABdJ380' 1u 7J 	}d3{D1A ! 
106OH- 2 FKO$AB?+HIJaO;J9<<'<))/<18
1, ! <06OH- 2
 +..{; $5<s%   06F/6GA GG-HHheadersmessageslitellm_paramsapi_keyapi_basec                     |S r>   rL   )r1   rl   rB   rm   rO   rn   ro   rp   s           r:   validate_environmentz%OllamaChatConfig.validate_environment   s	     r<   rF   c                 B    |d}|j                  d      r|}|S | d}|S )z{
        OPTIONAL

        Get the complete url for the request

        Some providers need `model` in `api_base`
        zhttp://localhost:11434z	/api/chat)endswith)r1   rp   ro   rB   rO   rn   rF   urls           r:   get_complete_urlz!OllamaChatConfig.get_complete_url   s<      /H[)C 
 Ji(C
r<   c           	      B   |j                  dd      }|j                  dd       }|j                  dd       }|j                  dd       }	|	|d<   |j                  dd       }
g }|D ]  }t        |t              r|j                  d      }|j	                  d	      }|t        |t
              rg }|D ]x  }t        di |}|d
   dk(  si }d|d   v rt        j                  |d   d         }t        t        |d   j	                  d      xs d|            }|j                  |       z |t        t        |      d	<   |j                  |        | j                         }|j                         D ]  \  }}||vs|||<    ||||d}|||d<   |
|
|d<   |||d<   |S )NrF   FrU   
keep_aliver_   rH   T)exclude_none
tool_callsrR   r]   	argumentsr^    r^   r{   )r]   )rB   rm   optionsrF   rL   )rh   r`   r   
model_dumprb   listr   rT   loadsr   r   appendr
   ra   r@   r4   )r1   rB   rm   rO   rn   rl   rF   rU   rx   r_   rH   new_messagesmrz   	new_toolstool
typed_toolr{   ollama_tool_callconfigkvdatas                          r:   transform_requestz"OllamaChatConfig.transform_request  s    !$$Xu5 $$Xt4$((t<
'++OTB*7'##GT2A9 LLdL3|,J%*Z*F24	&D!@!H4!HJ!&)Z7$&	&*Z*@@(,

:j3I+3V(WI+9%;%/
%;%?%?%G%M2*3&,( "(()9: ' /8T1l+"- 2 "LLNDAq'%&" #
 $&	
 #DN!DM!!+Dr<   raw_responsemodel_responselogging_objrequest_dataencoding	json_modec                 "   |j                  |d|j                  d |j                  d      d       |j                         }d|j                  d   _        |j                  dd      dk(  r|j                  d	      t        j                  |d
   d         }t        j                  d dt        t        j                                |j                  d|j                  d	            t        j                  |j                  d|            dddg      }||j                  d   _        d|j                  d   _        n,t        j                  di |d
   }||j                  d   _        t        t        j                               |_        d|z   |_        |j                  dt        j$                  |            }|j                  dt        j$                  |d
   d               }t'        |dt        j(                  ||||z                |S )Nr|   rp   )rl   rp   )inputro   original_responseadditional_argsr-   r   rU   rT   r_   messagecontentcall_r^   r{   r}   r]   )idr]   rR   r   rz   rz   zollama_chat/prompt_eval_count)rm   
eval_count)textusageprompt_tokenscompletion_tokenstotal_tokensrL   )	post_callr   rb   rT   choicesfinish_reasonr   rc   Messagestruuiduuid4dumpsr   inttimecreatedrB   token_counterr5   Usage)r1   rB   r   r   r   r   rm   rO   rn   r   ro   r   response_jsonfunction_callr   _messager   r   s                     r:   transform_responsez#OllamaChatConfig.transform_response@  s    	*//*..z:	 	 	
 %))+ 39q!/Xr*f4""?3? JJ}Y'?	'JKMoo !&c$**,&7%89$1$5$5 &(:(:?(K% *. - 1 1+} M*	% !+G" 18N""1%-6BN""1%3By)ABH08N""1%-!$TYY[!1-5%))*=w?T?T^f?gh)--!!}Y'?	'JK
 	MM+"3*->>	
 r<   error_messagestatus_codec                     t        |||      S )N)r   r   rl   r   )r1   r   r   rl   s       r:   get_error_classz OllamaChatConfig.get_error_class  s     #]G
 	
r<   streaming_responsesync_streamc                     t        |||      S )N)r   r   r   )$OllamaChatCompletionResponseIterator)r1   r   r   r   s       r:   get_model_response_iteratorz,OllamaChatConfig.get_model_response_iterator  s     41#
 	
r<   )NNNNNNNNNNNNNNNNN)NNr>   )F)0__name__
__module____qualname____doc__r   r   r   __annotations__r   floatr    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r   r+   r   r;   classmethodr@   rM   ra   boolrk   r   r   rr   rv   r   r   r   LiteLLMLoggingObjr   r	   r   r   r   r   r   r   __classcell__)r6   s   @r:   r   r   '   sp   (T #Hhsm"$(L(5/($(L(5/(!GXc]!!GXc]! $J$#'M8C='&*NHUO*D(3-!E8E?!!%K#%E8C= FHSM "Hhsm" #'(,(,!%!%$('+*.'+"#!%%)#!% $"&%43-4 uo4 uo	4
 #4 #4 SM4  }4 !4 e_4 sm4 tn4 4 c]4 }4  !4" #4$ 3-%4& 
'42 $ $
 
 N N N 	N
 N 
Nn "&"&

 
 '(	

 
 
 #
 3-
 

& "&3- # 	
    
2;; '(; 	;
 ; ; 
;P "&$(HH H &	H
 'H H '(H H H H #H D>H 
HT
 
/2
=B4==Q
	
 %*	

!(3-s1C]"RS

 

 D>	

r<   r   c                   6    e Zd Zdeeef   defdZdedefdZ	y)r   function_argsr/   c                 p    t        |t              ry	 t        j                  |       y# t        $ r Y yw xY w)NTF)r`   ra   rT   r   re   )r1   r   s     r:   _is_function_call_completez?OllamaChatCompletionResponseIterator._is_function_call_complete  s5    mT*	JJ}% 		s   ) 	55chunkc           	      T   	 	 ddl m}m} |d   j                  d      }|m|D ]h  }|j                  d      j                  d      }|&t	        |      dkD  s5| j                  |      }|sIt        t        j                               |d<   j  ||d   j                  dd	      |
      }|d   du r|j                  dd      }	 |||	      g}
n
 ||      g}
t        |j                  dd      |j                  dd      |j                  dd      |j                  dd      z         }t        t        t        j                               dt        t        j                               ||d   |
      S # t        $ r}t        d| d| dddi      d }~wt        $ r}|d }~ww xY w)Nr   )DeltaStreamingChoicesr   rz   r]   r{   r   r   r|   r   doneTdone_reasonr-   )deltar   )r   r   r   r   zchat.completion.chunkrB   )r   objectr   r   rB   r   z
KeyError: z', Got unexpected response from Ollama: i  zContent-Typezapplication/json)r   r   rl   )litellm.types.utilsr   r   rb   rg   r   r   r   r   r   r   r   r   KeyErrorr   re   )r1   r   r   r   rz   	tool_callr   is_function_call_completer   r   r   r   es                r:   chunk_parserz1OllamaChatCompletionResponseIterator.chunk_parser  s   U	8 D y)--l;J%!+I$-MM*$=$A$A+$NM$0S5G!5K484S4S)51 5.1$**,.?IdO ", i(,,Y;%E
 V}$ %		- @$#&3 %# -#ii(;Q?"'))L!"<"YY':A>))L!,-E 'tzz|$.DIIK(Gn   	$QC'NugV');< 
  	G	s7   AE5 	E5 E5 ,DE5 5	F'>FF' F""F'N)
r   r   r   r	   r   ra   r   r   r   r   rL   r<   r:   r   r     s5    c4i8H T V$ V+> Vr<   r   ))rT   r   r   typingr   r   r   r   r   r   r	   r
   httpx._modelsr   r   pydanticr   rc   )litellm.llms.base_llm.base_model_iteratorr   )litellm.llms.base_llm.chat.transformationr   r   litellm.types.llms.ollamar   r   litellm.types.llms.openair   r   r   r   r   r   common_utilsr   *litellm.litellm_core_utils.litellm_loggingr   _LiteLLMLoggingObjr   r   r   rL   r<   r:   <module>r      st      	 	 	 ,   O R L 
 C &X*t
z t
n`+D `r<   