
    AHjU                     T    d dl Z d dlmZmZmZmZmZmZ d dlZddl	m
Z
  G d d      Zy)    N)AnyDictIteratorListOptionalUnion   )UnauthorizedErrorc                   l   e Zd Zddedee   fdZdeeef   fdZ	 	 	 	 	 	 	 	 ddedeeeef      d	ee	   d
ee	   dee
   dee
   dee	   dee	   dee   dedeeeef   ej                  f   fdZ	 	 	 	 	 	 	 ddedeeeef      d	ee	   d
ee	   dee
   dee
   dee	   dee	   dee   deeeef      fdZy)
ChatClientNbase_urlapi_keyc                 >    |j                  d      | _        || _        y)a  
        Initialize the ChatClient.

        Args:
            base_url (str): The base URL of the LiteLLM proxy server (e.g., "http://localhost:8000")
            api_key (Optional[str]): API key for authentication. If provided, it will be sent as a Bearer token.
        /N)rstrip	_base_url_api_key)selfr   r   s      Q/root/tools/cai/cai_env/lib/python3.12/site-packages/litellm/proxy/client/chat.py__init__zChatClient.__init__
   s     "-    returnc                 J    ddi}| j                   rd| j                    |d<   |S )z
        Get the headers for API requests, including authorization if api_key is set.

        Returns:
            Dict[str, str]: Headers to use for API requests
        zContent-Typezapplication/jsonzBearer Authorization)r   )r   headerss     r   _get_headerszChatClient._get_headers   s0     "#56==)0'@GO$r   modelmessagestemperaturetop_pn
max_tokenspresence_penaltyfrequency_penaltyuserreturn_requestc                    | j                    d}||d}|||d<   |||d<   |||d<   |||d<   |||d<   |||d	<   |	|	|d
<   t        j                  d|| j                         |      }|
r|S t        j                         }	 |j                  |j                               }|j                          |j                         S # t        j                  j                  $ r*}|j                  j                  dk(  rt        |       d}~ww xY w)a  
        Create a chat completion.

        Args:
            model (str): The model to use for completion
            messages (List[Dict[str, str]]): The messages to generate a completion for
            temperature (Optional[float]): Sampling temperature between 0 and 2
            top_p (Optional[float]): Nucleus sampling parameter between 0 and 1
            n (Optional[int]): Number of completions to generate
            max_tokens (Optional[int]): Maximum number of tokens to generate
            presence_penalty (Optional[float]): Presence penalty between -2.0 and 2.0
            frequency_penalty (Optional[float]): Frequency penalty between -2.0 and 2.0
            user (Optional[str]): Unique identifier for the end user
            return_request (bool): If True, returns the prepared request object instead of executing it

        Returns:
            Union[Dict[str, Any], requests.Request]: Either the completion response from the server or
            a prepared request object if return_request is True

        Raises:
            UnauthorizedError: If the request fails with a 401 status code
            requests.exceptions.RequestException: If the request fails with any other error
        /chat/completions)r   r   Nr   r    r!   r"   r#   r$   r%   POST)r   json  )r   requestsRequestr   Sessionsendprepareraise_for_statusr*   
exceptions	HTTPErrorresponsestatus_coder
   )r   r   r   r   r    r!   r"   r#   r$   r%   r&   urldatarequestsessionr4   es                    r   completionszChatClient.completions!   s9   H   12 */HE ""-D!DM=DI!!+D''7D#$((9D$%DL""638I8I8KRVWN ""$	||GOO$56H%%'==?""",, 	zz%%,'**	s   >C D"%DDc
              #     K   | j                    d}
||dd}|||d<   |||d<   |||d<   |||d<   |||d	<   |||d
<   |	|	|d<   t        j                         }	 |j                  |
| j	                         |d      }|j                          |j                         D ]\  }|s|j                  d      }|j                  d      s)|dd }|j                         dk(  r y	 t        j                  |      }| ^ y# t        j                  $ r Y uw xY w# t        j                  j                  $ r*}|j                  j                   dk(  rt#        |       d}~ww xY ww)a  
        Create a streaming chat completion.

        Args:
            model (str): The model to use for completion
            messages (List[Dict[str, str]]): The messages to generate a completion for
            temperature (Optional[float]): Sampling temperature between 0 and 2
            top_p (Optional[float]): Nucleus sampling parameter between 0 and 1
            n (Optional[int]): Number of completions to generate
            max_tokens (Optional[int]): Maximum number of tokens to generate
            presence_penalty (Optional[float]): Presence penalty between -2.0 and 2.0
            frequency_penalty (Optional[float]): Frequency penalty between -2.0 and 2.0
            user (Optional[str]): Unique identifier for the end user

        Yields:
            Dict[str, Any]: Streaming response chunks from the server

        Raises:
            UnauthorizedError: If the request fails with a 401 status code
            requests.exceptions.RequestException: If the request fails with any other error
        r(   T)r   r   streamNr   r    r!   r"   r#   r$   r%   )r   r*   r=   zutf-8zdata:    z[DONE]r+   )r   r,   r.   postr   r1   
iter_linesdecode
startswithstripr*   loadsJSONDecodeErrorr2   r3   r4   r5   r
   )r   r   r   r   r    r!   r"   r#   r$   r%   r6   r7   r9   r4   linedata_strchunkr:   s                     r   completions_streamzChatClient.completions_streamj   s    B   12 */HPTU ""-D!DM=DI!!+D''7D#$((9D$%DL ""$	||T..0tD $ H %%' !++- %;;w/Dx0#'8#>>+x7!%$(JJx$8E"'K%  $33 %$% "",, 	zz%%,'**	sa   AE$AD '"D 
D #E$%D>D  E$DD DD E!7%EE!!E$)N)NNNNNNNF)NNNNNNN)__name__
__module____qualname__strr   r   r   r   r   floatintboolr   r   r,   r-   r;   r   rI    r   r   r   r   	   s   	  	 x} 	 
d38n 
  (,!%$(,0-1"$GG tCH~&G e_	G
 G C=G SMG #5/G $E?G smG G 
tCH~x///	0GZ (,!%$(,0-1"OO tCH~&O e_	O
 O C=O SMO #5/O $E?O smO 
$sCx.	!Or   r   )r*   typingr   r   r   r   r   r   r,   r2   r
   r   rQ   r   r   <module>rS      s      = =  )p pr   