
    AHj;                        d dl Z d dlmZmZmZmZ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 d dlmZ 	 	 d"dee   ded	   d
ee   dee   deeeee   f   f
dZ	 	 d"deded	   d
ee   dee   deeeee   f   f
dZ	 d#dee   d
ee   dee   fdZ	 	 	 d$dee   ded	   d
ee   dee   def
dZ	 d#dee   d
ee   deeef   fdZ	 	 d%deded	   dee   dee   fdZdee   defdZdedee   fdZ	 	 d%dee   ded	   dee   defdZ	 	 d%dee   ded	   d
ee   defdZ	 	 d%dee   ded   d
ee   defdZ dedefdZ!dedefd Z"dede#fd!Z$y)&    N)AnyListLiteralOptionalTuple)verbose_logger)Batch)	CallTypes	ModelInfoUsage)token_counterfile_content_dictionarycustom_llm_provider)openaiazure	vertex_aihosted_vllm	anthropic
model_name
model_inforeturnc                 f   K   t        || ||      }t        | ||      }t        | |      }|||fS w)aO  
    Calculate the cost and usage of a batch.

    Args:
        model_info: Optional deployment-level model info with custom batch
            pricing. Threaded through to batch_cost_calculator so that
            deployment-specific pricing (e.g. input_cost_per_token_batches)
            is used instead of the global cost map.
    )r   r   r   r   r   r   r   )_batch_cost_calculator,_get_batch_job_total_usage_from_file_content#_get_batch_models_from_file_content)r   r   r   r   
batch_costbatch_usagebatch_modelss          S/root/tools/cai/cai_env/lib/python3.12/site-packages/litellm/batches/batch_utils.pycalculate_batch_cost_and_usager!      sS     " (/ 7	J ? 7/K
 7L {L00s   /1batchlitellm_paramsc                    K   t        | ||       d{   }t        |||      }t        |||      }t        ||      }|||fS 7 1w)a*  Helper function to process a completed batch and handle logging

    Args:
        batch: The batch object
        custom_llm_provider: The LLM provider
        model_name: Optional model name
        litellm_params: Optional litellm parameters containing credentials (api_key, api_base, etc.)
    )r#   N)r   r   r   r   ),_get_batch_output_file_content_as_dictionaryr   r   r   )r"   r   r   r#   r   r   r   r   s           r    _handle_completed_batchr&   .   sp     " %Q">% 
 (/ 7J
 ? 7/K 7L {L00)s   AA2Ac                     |r|gS g }| D ]>  }t        |      st        |      }|j                  d      }|s.|j                  |       @ |S )z.
    Get the models from the file content
    model)_batch_response_was_successful(_get_response_from_batch_job_output_filegetappend)r   r   r   _item_response_body_models         r    r   r   V   s^     |L( ,)%0EeLN#''0F##F+,     c                     |dk(  r)|r't        | |      \  }}t        j                  d|       |S t        | ||      }t        j                  d|       |S )zC
    Calculate the cost of a batch based on the output file id
    r   zvertex_ai_total_cost=%s)r   r   r   total_cost=%s)(calculate_vertex_ai_batch_cost_and_usager   debug%_get_batch_job_cost_from_file_content)r   r   r   r   r   _
total_costs          r    r   r   i   sg     k)j@#Z

A 	6
C 7 7/J
 *5r0   vertex_ai_batch_responsesc                 2   ddl m} d}d}d}d}|xs d}| D ]  }|j                  d      }	|	|	j                  di       }
|
j                  dd      xs d}|
j                  d	d      xs d}|
j                  d
d      xs ||z   }t        |||      }	  |||d      \  }}|||z   z  }||z  }||z  }||z  } t        j                  d||||       |t        |||      fS # t        $ r)}t        j                  dt        |             Y d}~gd}~ww xY w)a+  
    Calculate both cost and usage from Vertex AI batch responses.

    Vertex AI batch output lines have format:
      {"request": ..., "status": "", "response": {"candidates": [...], "usageMetadata": {...}}}

    usageMetadata contains promptTokenCount, candidatesTokenCount, totalTokenCount.
    r   batch_cost_calculator        zgemini-2.0-flash-001responseNusageMetadatapromptTokenCountcandidatesTokenCounttotalTokenCount)prompt_tokenscompletion_tokenstotal_tokensr   )usager(   r   z3vertex_ai batch cost calculation error for line: %szAvertex_ai batch cost: cost=%s, prompt=%d, completion=%d, total=%drD   rB   rC   )	litellm.cost_calculatorr;   r+   r   	Exceptionr   r4   strinfo)r8   r   r;   r7   rD   rB   rC   actual_model_namer=   response_bodyusage_metadata_prompt_completion_total
line_usagep_costc_costes                     r    r3   r3      sz    >JLM"<&<-  Z0 &**?B? $$%7;@q$(()?CHq##$5q9Tg>S!)


	2 '$/NFF
 &6/)J 	 [(=@ K u!#+  #  	  Es1v 	s   C$$	D-DDc                 ,  K   ddl m} ddlm} |dk(  rt	        d      | j
                  t	        d      | j
                  } ||      }|r?	 |j                  d      d	   j                  d
      d   }t        j                  d|        ||d}t        |      }	|j                  |	        |di | d{   }
t        |
j                        S # t        t        f$ r/}t        j                  d| j
                   d|        Y d}~d}~ww xY w7 Zw)aZ  
    Get the batch output file content as a list of dictionaries

    Args:
        batch: The batch object
        custom_llm_provider: The LLM provider
        litellm_params: Optional litellm parameters containing credentials (api_key, api_base, etc.)
                       Required for Azure and other providers that need authentication
    r   )afile_content)"_is_base64_encoded_unified_file_idr   z1Vertex AI does not support file content retrievalNz3Output file id is None cannot retrieve file contentzllm_output_file_id,   ;z3Extracted LLM output file ID from unified file ID: z;Failed to extract LLM output file ID from unified file ID: z	, error: )file_idr    )litellm.files.mainrV   1litellm.proxy.openai_files_endpoints.common_utilsrW   
ValueErroroutput_file_idsplitr   r4   
IndexErrorAttributeErrorerror _extract_file_access_credentialsupdate_get_file_content_as_dictionarycontent)r"   r   r#   rV   rW   rZ   is_base64_unified_file_idrT   file_content_kwargscredentials_file_contents              r    r%   r%      s7      1 k)LMM#NOO""G B7 K 
	/556KLQOUUG   EgYO 2 3>BK{+'>*=>>M*=+@+@AA! N+ 	  MeNbNbMcclmnlop 	 ?s<   A
D>C ,D7D8DD %D
D
DDc                 >    i }| rg d}|D ]  }|| v s| |   ||<    |S )a  
    Extract credentials from litellm_params for file access operations.

    This method extracts relevant authentication and configuration parameters
    needed for accessing files across different providers (Azure, Vertex AI, etc.).

    Args:
        litellm_params: Dictionary containing litellm parameters with credentials

    Returns:
        Dictionary containing only the credentials needed for file access
    )api_keyapi_baseapi_versionorganizationazure_ad_tokenazure_ad_token_providervertex_projectvertex_locationvertex_credentialstimeoutmax_retriesr[   )r#   rj   credential_keyskeys       r    rd   rd     sC     K
 # 	7Cn$#1##6C 	7 r0   file_contentc                 @   	 | j                  d      }g }|j                         j                  d      D ])  }|s|j                  t	        j
                  |             + t        j                  dt	        j                  |d             |S # t        $ r}|d}~ww xY w)zO
    Get the file content as a list of dictionaries from JSON Lines format
    zutf-8
zjson_objects=%s   indentN)
decodestripr`   r,   jsonloadsr   r4   dumpsrH   )rz   _file_content_strjson_objectslinerT   s        r    rf   rf   &  s    
(//8%++-33D9 	6D##DJJt$45	6 	.

<PQ0RS s   7B AB 	BBBc                    ddl m} 	 d}t        j                  dt	        j
                  | d             | D ]  }t        |      st        |      }|5t        |      }|j                  dd	      } |||||
      \  }	}
||	|
z   z  }n3|t        j                  ||t        j                  j                        z  }t        j                  d|        |S # t        $ r}t        j                   d|       |d}~ww xY w)z;
    Get the cost of a batch job from the file content
    r   r:   r<   zfile_content_dictionary=%sr}   r~   Nr(    )rE   r(   r   r   )completion_responser   	call_typer2   z.error in _get_batch_job_cost_from_file_content)rG   r;   r   r4   r   r   r)   r*   '_get_batch_job_usage_from_response_bodyr+   litellmcompletion_costr
   aretrieve_batchvaluerH   rc   )r   r   r   r;   r7   r-   r.   rE   r(   prompt_costr   rT   s               r    r5   r5   7  s    >
($**5LUV*W	
 - 	BE-e4!I%!P)CNSE*..w;E3H##,?#-	40K +"??J'"9"9,:,?"+";";"A"A# J
 $$_jA'	B(  MqQs   =C BC 	C;C66C;c                    |dk(  r|rt        | |      \  }}|S d}d}d}| D ]Q  }t        |      st        |      }	t        |	      }
||
j                  z  }||
j
                  z  }||
j                  z  }S t        |||      S )z=
    Get the tokens of a batch job from the file content
    r   r   rF   )r3   r)   r*   r   rD   rB   rC   r   )r   r   r   r6   r   rD   rB   rC   r-   r.   rE   s              r    r   r   c  s     k)jA#Z
;  LM( 9)%0EeLNB>REE...LU000M!8!889 !#+ r0   )r   r   r   c                     d}d}| D ]Q  }|j                  di       }|j                  d|xs d      }|j                  dg       }|s@t        ||      }	||	z  }S t        ||z   ||      S )z
    Count the number of tokens in the input file

    Used for batch rate limiting to count the number of tokens in the input file
    r   bodyr(   r   messages)r(   r   rF   )r+   r   r   )
r   r   r   rB   rC   r-   r   r(   r   item_tokenss
             r    _get_batch_job_input_file_usager     s     M( )yy$*"2388J+'ehGK[(M) "%66#+ r0   rL   c                 H    | j                  dd      xs i }t        di |}|S )z>
    Get the tokens of a batch job from the response body
    rE   Nr[   )r+   r   )rL   _usage_dictrE   s      r    r   r     s-      ##GT28bK';'ELr0   batch_job_output_filec                 ^    | j                  dd      xs i }|j                  dd      xs i }|S )z9
    Get the response from the batch job output file
    r=   Nr   r+   )r   	_responser.   s      r    r*   r*     s6     ,//
DAGRI]]6406BNr0   c                 X    | j                  dd      xs i }|j                  dd      dk(  S )z7
    Check if the batch job response status == 200
    r=   Nstatus_code   r   )r   r   s     r    r)   r)     s1     ,//
DAGRI==-44r0   )NN)N)r   NN)r   N)%r   typingr   r   r   r   r   r   litellm._loggingr   litellm.types.llms.openair	   litellm.types.utilsr
   r   r   litellm.utilsr   dictrI   floatr!   r&   r   r   r3   r%   rd   bytesrf   r5   r   r   r   r*   boolr)   r[   r0   r    <module>r      s    6 6  + + ; ; ' !%&* 1!$Z 1 B 1
  1 # 1 5%c"# 1P !%%)%1%1 B%1
 %1 TN%1 5%c"#%1T !%!$Z 
#Y. 	 $&*!$Z B
  # > !%@#Dz@@ 5%<@N 	%)5B5B B5B
 TN5B 
$Z5Bp"Xd^ " "J% DJ * 	&*)!$Z) B)
 #) )` 	 $ !$Z  B 
    J DL $!$Z !?@  	:4 E D S 5$ 54 5r0   