
    jA;                         d dl Z d dlmZmZmZmZmZmZmZm	Z	m
Z
 d dlmZ d dlZd dlmZ d dlmZ d dlmZmZmZmZ d dlmZ d dlmZmZmZ  G d	 d
      Z G d d      Zy)    N)	AnyDictListOptionalTypeUnioncastget_type_hintsoverload)	BaseModel)verbose_logger)BaseResponsesAPIConfig)ResponseAPIUsage!ResponsesAPIOptionalRequestParamsResponsesAPIResponseResponseText)DecodedResponseId)PromptTokensDetailsSpecialEnumsUsagec                   x   e Zd ZdZedeee      dedee	   dee   def
d       Z
e	 d!ded	ed
edeee      def
d       Zedeeef   defd       Zee	 d!dedee   deeeef      defd              Zee	 d!deeef   dee   deeeef      deeef   fd              Ze	 d!deeeeef   f   dee   deeeef      deeeeef   f   fd       Zedee   dee   dedefd       Zededefd       Zedee   dee   fd       Zededefd       Ze	 d!deeed   ef      ded   ded   fd        Zy)"ResponsesAPIRequestUtilsz2Helper utils for constructing ResponseAPI requestssupported_paramsnon_default_paramsdrop_paramscustom_llm_providermodelc           	          | y i }|j                         D ]  }|| vs||   ||<    |r9t        j                  du s||du ry t        j                  d| d| d| d      y )NTi  z does not support parameters: z, for model=zf. To drop these, set `litellm.drop_params=True` or for proxy:

`litellm_settings:
 drop_params: true`
)status_codemessage)keyslitellmr   UnsupportedParamsError)r   r   r   r   r   unsupported_paramsks          p/Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/litellm/responses/utils.py_check_valid_argz)ResponsesAPIRequestUtils._check_valid_arg    s     ##((*A(((:1(="1% + ""d*'K4,?44 #233QRdQeeqrwqx  yc  d      Nresponses_api_provider_configresponse_api_optional_paramsallowed_openai_paramsreturnc                 (   ddl m} |j                  |       }t        t        |      }t
        j                  ||xs g z   |t        j                  |j                  |        |j                  || t        j                        } ||||xs g       }|S )aS  
        Get optional parameters for the responses API.

        Args:
            params: Dictionary of all parameters
            model: The model name
            responses_api_provider_config: The provider configuration for responses API

        Returns:
            A dictionary of supported parameters for the responses API
        r   )_apply_openai_param_overrides)r   r   r   r   r   )r*   r   r   )optional_paramsr   r+   )litellm.utilsr.   get_supported_openai_paramsr	   r   r   r'   r"   r   r   map_openai_params)r   r)   r*   r+   r.   r   r   mapped_paramss           r&   !get_optional_params_responses_apiz:ResponsesAPIRequestUtils.get_optional_params_responses_api9   s    $ 	@ 9TT
 "$(DE 11-1F1L"M1++ = Q Q 	2 	
 6GG)E++ H 
 6)1"7"=2
 r(   paramsc                    ddl m} t        t              j	                         }| j                  dd      }| j                  di       }| j                  dd      }|j                  | ||||D ci c]  }|d c}dg      }d	|v rt        j                  |d	         }||d	<   d
|v r+ddl m	}	  |	|d
         }
|
|
|d
<   n|j                  d
d       t        t        |      S c c}w )a  
        Filter parameters to only include those defined in ResponsesAPIOptionalRequestParams.

        Args:
            params: Dictionary of parameters to filter

        Returns:
            ResponsesAPIOptionalRequestParams instance with only the valid parameters
        r   )PreProcessNonDefaultParamsr   Nkwargsadditional_drop_paramsinput)passed_paramsspecial_paramsr   r9   default_param_values#additional_endpoint_specific_paramsprevious_response_idmetadata)add_openai_metadata)r0   r7   r
   r   r!   pop#base_pre_process_non_default_paramsr   <decode_previous_response_id_to_original_previous_response_idrA   r	   )r5   r7   
valid_keysr   r<   r9   r%   r   decoded_previous_response_idrA   converted_metadatas              r&   )get_requested_response_api_optional_paramzBResponsesAPIRequestUtils.get_requested_response_api_optional_paramm   s    	=#$EFKKM
$jj)>EHb1!',Dd!K&JJ$-$7'=7A%Bz!agz%B5<I K  	 "%77+C  ,A  ,A"#9:,( :V56++9!45G
5S!T!-1C":."&&z4857IJJ+ &Cs   -
C!responses_api_responselitellm_metadatac                      y N rI   r   rJ   s      r&   /_update_responses_api_response_id_with_model_idzHResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id        	r(   c                      y rL   rM   rN   s      r&   rO   zHResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id   rP   r(   c                    |xs i }|j                  di       xs i }|j                  d      }t        | t              r| d   n| j                  }t        j                  |||      }t        | t              r|| d<   | S || _        | S )zUpdate the responses_api_response_id with model_id and custom_llm_provider.

        Handles both ``ResponsesAPIResponse`` objects and plain dictionaries returned
        by some streaming providers.
        
model_infoid)model_idr   response_id)get
isinstancedictrT   r    _build_responses_api_response_id)rI   r   rJ   rS   rU   rV   
updated_ids          r&   rO   zHResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id   s     ,1r%5%9%9,%K%Qr
>>$'
 0$7 #4('** 	 .NN 3# O 

 ,d3+5"4( &% )3"%%%r(   rU   rV   c                     t        t        j                  j                        j	                  | ||      }t        j                  |j                  d            j                  d      }d| S )z#Build the responses_api_response_idutf-8resp_)	strr   %LITELLM_MANAGED_RESPONSE_COMPLETE_STRvalueformatbase64	b64encodeencodedecode)r   rU   rV   assembled_idbase64_encoded_ids        r&   rZ   z9ResponsesAPIRequestUtils._build_responses_api_response_id   sl      >>DD

&$h
< 	 "(!1!1,2E2Eg2N!O!V!V"
 ()**r(   c                 "   	 | j                  dd      }t        j                  |j                  d            j	                  d      }d|vrt        dd|       S |j                  d      }d}d}t        |      dk\  rF|d   }|d	   }|d
   }|j                  dd      }|j                  dd      }|j                  dd      }	n| }	t        |||	      S # t        $ r3}
t        j                  d|  d|
        t        dd|       cY d}
~
S d}
~
ww xY w)z
        Decode the responses_api_response_id

        Returns:
            DecodedResponseId: Structured tuple with custom_llm_provider, model_id, and response_id
        r^    r]   ;N)r   rU   rV      r         zlitellm:custom_llm_provider:z	model_id:zresponse_id:zError decoding response_id 'z': )replacerc   	b64decodere   rf   r   splitlen	Exceptionr   debug)rV   
cleaned_id
decoded_idpartsr   rU   custom_llm_provider_partmodel_id_partresponse_partdecoded_response_ides              r&   !_decode_responses_api_response_idz:ResponsesAPIRequestUtils._decode_responses_api_response_id   sE   -	$,,Wb9J))**;*;G*DELLWUJ *$((,! +  $$S)E #'H E
a+08( %a %a&>&F&F2B'# )00bA&3&;&;NB&O#&1#$$7!/ 
  	  #?}CPQs!ST$$(' 	s%   AC A8C 	D(D	D	Dc                 \    | yt         j                  |       }|j                  d      xs dS )z%Get the model_id from the response_idNrU   r   r}   rW   )rV   r{   s     r&   get_model_id_from_response_idz6ResponsesAPIRequestUtils.get_model_id_from_response_id  s8     $FF{S 	 #&&z2:d:r(   r?   c                 P    t         j                  |       }|j                  d|       S )aS  
        Decode the previous_response_id to the original previous_response_id

        Why?
            - LiteLLM encodes the `custom_llm_provider` and `model_id` into the `previous_response_id` this helps with maintaining session consistency when load balancing multiple deployments of the same model.
            - We cannot send the litellm encoded b64 to the upstream llm api, hence we decode it to the original `previous_response_id`

        Args:
            previous_response_id: The previous_response_id to decode

        Returns:
            The original previous_response_id
        rV   r   )r?   r{   s     r&   rD   zUResponsesAPIRequestUtils.decode_previous_response_id_to_original_previous_response_id'  s0    $ %FF$ 	
 #&&}6JKKr(   text_formatr   textr   c                 n    | 2|0ddl m}  ||       }| d|d   |d   d   |d   d   |d   d   d	i}|S |S )
at  
        Convert text_format parameter to text parameter for the responses API.

        Args:
            text_format: Pydantic model class or dict to convert to response format
            text: Existing text parameter (if provided, text_format is ignored)

        Returns:
            ResponseText object with the converted format, or None if conversion fails
        r   )type_to_response_format_paramrb   typejson_schemanameschemastrict)r   r   r   r   ) litellm.llms.base_llm.base_utilsr   )r   r   r   response_formats       r&   !convert_text_format_to_text_paramz:ResponsesAPIRequestUtils.convert_text_format_to_text_param?  so     "t|V <KHO*  / 7 / >v F"1-"@"J"1-"@"J	 r(   rL   )__name__
__module____qualname____doc__staticmethodr   r   r_   r   boolr'   r   r   r4   r   rH   r   r   rO   r   rZ   r   r}   r   rD   r   rY   r   rM   r(   r&   r   r      s   <"49-  d^ &c]	
  0 
 6:	11'=1 'H1  (S	2	1
 
1 1f .KS#X.K	*.K .Kb  6: 4%c] #4S>2 
	    6: $S#X%c] #4S>2 
c3h	    6:& %&:DcN&J K&%c]& #4S>2& 
#T#s(^3	4	& &B +%c]+3-+ + 
	+ + 66	6 6p ;8C= ;Xc] ; ; L!L	L L.  *.eD$5t$;<=~& 
.	! r(   r   c                   Z    e Zd Zedeeef   defd       Zede	eeef      de
fd       Zy)ResponseAPILoggingUtilsusager,   c                 8    t        | t              ryd| v rd| v ryy)z1returns True if usage is from OpenAI Response APITinput_tokensoutput_tokensF)rX   r   )r   s    r&   _is_response_api_usagez.ResponseAPILoggingUtils._is_response_api_usagec  s'     e-.U"%'?r(   usage_inputc                    | t        ddd      S t        | t              rt        di | n| }|j                  xs d}|j
                  xs d}d}|j                  r5t        |j                  j                  |j                  j                        }t        ||||z   |      }t        |d      r#|j                  t        |d|j                         |S )z7Tranforms the ResponseAPIUsage object to a Usage objectNr   )prompt_tokenscompletion_tokenstotal_tokens)cached_tokensaudio_tokens)r   r   r   prompt_tokens_detailscostrM   )r   rX   rY   r   r   r   input_tokens_detailsr   r   r   hasattrr   setattr)r   response_api_usager   r   r   
chat_usages         r&   +_transform_response_api_usage_to_chat_usagezCResponseAPILoggingUtils._transform_response_api_usage_to_chat_usagel  s    
 "#  +t, +{+ 	
 0<<A!3!A!A!FQ?C22$70EESS/DDQQ%! '/&)::"7	

 %v.3E3J3J3VJ(:(?(?@r(   N)r   r   r   r   r   rY   r   r   r   r   r   r   rM   r(   r&   r   r   b  sa    eD2B,B&C    "eD*:$:;<"	" "r(   r   )rc   typingr   r   r   r   r   r   r	   r
   r   pydanticr   r"   litellm._loggingr   .litellm.llms.base_llm.responses.transformationr   litellm.types.llms.openair   r   r   r   litellm.types.responses.mainr   litellm.types.utilsr   r   r   r   r   rM   r(   r&   <module>r      sQ    
 
 
   + Q  ; H HB BJ
- -r(   