
    gB                        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
 d dlmZmZ d dl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! d
dl"m#Z#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)HeadersResponse)convert_to_ollama_imagecustom_prompt	ollama_pt)BaseModelResponseIterator)
BaseConfigBaseLLMException)get_secret_str)AllMessageValuesChatCompletionUsageBlock)GenericStreamingChunkModelInfoBaseModelResponseProviderField   )OllamaError_convert_image)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<   dZee   ed<   dZee	   ed<   dZee   ed<   dZee   ed<   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d9d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Ze fd       Zdee    fdZ!defdZ"de#de#dede$de#f
dZ%de#de$fd Z&de#dee   fd!Z'dede(fd"Z)d#ed$ed%e*e#e+f   de,fd&Z-	 	 d:ded'e.d(e/d)e0d*e#d+ee1   de#d,e#d-ed.ee   d/ee$   de/fd0Z2ded+ee1   de#d,e#d%e#de#fd1Z3	 	 d:d%e#ded+ee1   de#d.ee   d2ee   de#fd3Z4	 d;d2edede#d4ee$   def
d5Z5	 d<d6e*e6e   e7e   e/f   d7e$d/ee$   fd8Z8 xZ9S )=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                     t               }|j                         D ]%  \  }}|dk7  s|t        | j                  ||       ' y )Nself)localsitemssetattr	__class__)r3   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   locals_keyvalues                         b/var/www/openai/venv/lib/python3.12/site-packages/litellm/llms/ollama/completion/transformation.py__init__zOllamaConfig.__init__c   s;    * (!--/JCf}!2U3 *    c                      t         |          S N)super
get_config)clsr7   s    r;   rA   zOllamaConfig.get_config}   s    w!##r=   c                 "    t        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_name
field_typefield_descriptionfield_value)r   )r3   s    r;   get_required_paramsz OllamaConfig.get_required_params   s"     %#"87	
 	
r=   modelc                 
    g dS )N)
max_tokensstreamr.   r(   r)   frequency_penaltyr*   response_format )r3   rK   s     r;   get_supported_openai_paramsz(OllamaConfig.get_supported_openai_params   s    	
 		
r=   non_default_paramsoptional_paramsdrop_paramsc                    |j                         D ]p  \  }}|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(  sRt        |t              sc|d   dk(  sld|d<   r |S )NrM   r,   rN   r(   r)   r.   rO   r'   r*   rP   typejson_objectjsonformat)r5   
isinstancedict)r3   rS   rT   rK   rU   paramr:   s          r;   map_openai_paramszOllamaConfig.map_openai_params   s     /446LE5$16. ,1)%16.*/'+0(++49 01*/'))j.E=M106OH-# 7& r=   ollama_model_infoc                 d    t        |j                  dd      xs d      }d|j                         v S )zn
        Check if the 'template' field in the ollama_model_info contains a 'tools' or 'function' key.
        r0    tools)strgetlower)r3   r_   	_templates      r;   _supports_function_callingz'OllamaConfig._supports_function_calling   s3     .22:rBHbI	)//+++r=   c                 h    |j                  di       }|j                         D ]  \  }}d|v s|c S  y )N
model_infocontext_length)rd   r5   )r3   r_   _model_infokvs        r;   _get_max_tokenszOllamaConfig._get_max_tokens   s=    -11,C%%'DAq1$ ( r=   c                    |j                  d      s|j                  d      r|j                  dd      d   }t        d      xs d}	 t        j                  j                  | dd|i	      }|j                         }| j                  |      }t        |dd| j                  |      dd|||	      S # t        $ r}t        d
| d|       d}~ww xY w)zc
        curl http://localhost:11434/api/show -d '{
          "name": "mistral"
        }'
        ollama/zollama_chat//   OLLAMA_API_BASEzhttp://localhost:11434z	/api/showname)urlrY   z*OllamaError: Error getting model info for zI. Set Ollama API Base via `OLLAMA_API_BASE` environment variable. Error: Nollamachatg        )	r9   litellm_providermodesupports_function_callinginput_cost_per_tokenoutput_cost_per_tokenrM   max_input_tokensmax_output_tokens)
startswithsplitr   litellmmodule_level_clientpost	ExceptionrY   rn   r   rg   )r3   rK   api_baseresponseeri   _max_tokenss          r;   get_model_infozOllamaConfig.get_model_info   s    I&%*:*:>*JKKQ'*E!"34P8P	2277j	*e_ 8 H ]]_
%)%9%9*%E%&*&E&Ej&Q!$"%"()

 
	
  	<UG  DM  NO  MP  Q 	s   &B2 2	C;CCerror_messagestatus_codeheadersc                     t        |||      S )N)r   messager   )r   )r3   r   r   r   s       r;   get_error_classzOllamaConfig.get_error_class   s     #]G
 	
r=   raw_responsemodel_responselogging_objrequest_datamessageslitellm_paramsencodingapi_key	json_modec           
         |j                         }d|j                  d   _        |j                  dd      dk(  rt        j                  |d         }t        j                  d dt        t        j                                |d   t        j                  |d	         d
ddg      }||j                  d   _        d|j                  d   _        n!|d   |j                  d   j                  _        t        t        j                               |_        d|z   |_        |j                  dd      }|j                  dt#        |	j%                  |d                  }|j                  dt#        |j                  dt'                     j                  dd                  }t)        |dt        j*                  ||||z                |S )Nr*   r   rZ   ra   rY   r   call_rt   	arguments)rt   r   function)idr   rW   )content
tool_callsr   rp   promptprompt_eval_countrQ   )disallowed_special
eval_countr   r   usageprompt_tokenscompletion_tokenstotal_tokens)rY   choicesfinish_reasonrd   loadsr   Messagerc   uuiduuid4dumpsr   r   inttimecreatedrK   lenencoder\   r6   Usage)r3   rK   r   r   r   r   r   rT   r   r   r   r   response_jsonfunction_callr   _promptr   r   s                     r;   transform_responsezOllamaConfig.transform_response   s    %))+28q!/Hb)V3 JJ}Z'@AMoo !&c$**,&7%89$1&$9)-M+4N)O% !+	G 18N""1%-6BN""1%38Ej8QN""1%--5!$TYY[!1(50""8R0%))X__WQS_%T!U
 *--#m//	46BFFyRTUV
 	MM+"3*->>	
 r=   c                    |j                  d      xs t        j                  }||v r||   }t        |d   |d   |d   |      }n/t	        ||      }	t        |	t              r|	d   |	d   }
}|
|d<   n|	}|j                  d	d
      }|j                  dd       }|j                  dd       }
||||d}|||d<   |
%|
D cg c]  }t        t        |             c}|d<   |S c c}w )Ncustom_prompt_dictrolesinitial_prompt_valuefinal_prompt_value)	role_dictr   r   r   )rK   r   r   imagesrN   FrZ   )rK   r   optionsrN   )
rd   r   r   r   r   r[   r\   popr   r   )r3   rK   r   rT   r   r   r   model_prompt_detailsollama_promptmodified_promptr   rN   rZ   dataimages                  r;   transform_requestzOllamaConfig.transform_request&  s4    34R8R8R 	 &&#5e#< ).w7%9:P%Q#78L#M!	M (ehGO/40#H-#H-  & -3) / $$Xu5 $$Xt4 $$Xt4#&	
 #DNLRLR56u=>FDN 	s   ?C"r   c                     |S r?   rQ   )r3   r   rK   r   rT   r   r   s          r;   validate_environmentz!OllamaConfig.validate_environmentW  s	     r=   rN   c                 :    |j                  d      r|}|S | d}|S )z{
        OPTIONAL

        Get the complete url for the request

        Some providers need `model` in `api_base`
        z/api/generate)endswith)r3   r   rK   rT   rN   ru   s         r;   get_complete_urlzOllamaConfig.get_complete_urlb  s1     _-C 
 Jm,C
r=   streaming_responsesync_streamc                     t        |||      S )N)r   r   r   )$OllamaTextCompletionResponseIterator)r3   r   r   r   s       r;   get_model_response_iteratorz(OllamaConfig.get_model_response_iteratorw  s     41#
 	
r=   )NNNNNNNNNNNNNNNNNN)NNr?   )F):__name__
__module____qualname____doc__r   r   r   __annotations__r    floatr!   r"   r#   r$   r%   r&   r'   r(   r)   r*   listr+   r,   r-   r.   r/   rc   r0   r<   classmethodrA   r   r   rJ   rR   r\   boolr^   rg   rn   r   r   r	   r
   r   r   r   r   LiteLLMLoggingObjr   r   r   r   r   r   r   r   __classcell__)r7   s   @r;   r   r   #   s   (T #Hhsm"$(L(5/($(L(5/(!GXc]!!GXc]!!GXc]! $J$#'M8C='&*NHUO*#'K%'D(3- 	(4.  "E8E?!!%K#%E8C=!E8E?! FHSM "Hhsm" #'(,(,!%!%!%$('+*.'+"#!%%)#!% $"&'43-4 uo4 uo	4
 #4 #4 #4 SM4  }4 !4 e_4 sm4 tn4 4 c]4  }!4" #4$ %4& 3-'4( 
)44 $ $	
T-%8 	


 

   	
  
8,D ,T , (3- "
C "
M "
H
 
/2
=B4==Q
	
$ "&$(66 6 &	6
 '6 6 '(6 6 6 6 #6 D>6 
6p// '(/ 	/
 / / 
/n "&"&		 	 '(		
 	 #	 3-	 
	  "&  	
  
2 %*	

!(3-s1C]"RS

 

 D>	

r=   r   c                   ,    e Zd ZdedefdZdedefdZy)r   str_liner1   c                 J    | j                  t        j                  |            S r?   )chunk_parserrY   r   )r3   r   s     r;   _handle_string_chunkz9OllamaTextCompletionResponseIterator._handle_string_chunk  s      H!566r=   chunkc                 V   	 d|v rt        d|       d}d}d }|d   du rPd}d}d}|j                  dd       }|j                  d	d       }d }||t        ||||z   
      }t        ||||      S |d   r|d   }t        ||dd       S t        d|       # t         $ r}|d }~ww xY w)NerrorzOllama Error - ra   FdoneTr*   r   r   r   )textis_finishedr   r   r   zUnable to parse ollama chunk - )r   rd   r   r   )	r3   r   r   r   r   r   r   r   r   s	            r;   r   z1OllamaTextCompletionResponseIterator.chunk_parser  s   &	%/% 9::DK MV}$" &3899=PRV3W!,1IIlD,I
<@$0Z5K4&7*4%6%CE
 - +"/	  z"Z(, +"(	   "A% IJJ 	G	s$   A.B 1B 
B 	B(!B##B(N)r   r   r   rc   r   r   r\   r   rQ   r=   r;   r   r     s*    7S 75J 7'$ '+@ 'r=   r   )+rY   r   r   typingr   r   r   r   r   r   r	   httpx._modelsr
   r   r   3litellm.litellm_core_utils.prompt_templates.factoryr   r   r   )litellm.llms.base_llm.base_model_iteratorr   )litellm.llms.base_llm.chat.transformationr   r   litellm.secret_managers.mainr   litellm.types.llms.openair   r   litellm.types.utilsr   r   r   r   common_utilsr   r   *litellm.litellm_core_utils.litellm_loggingr   _LiteLLMLoggingObjr   r   r   rQ   r=   r;   <module>r      ss       U U U +  
 P R 7 P  7X*^
: ^
B++D +r=   