
    j/                     t   d dl Z d dlZd dlmZmZmZmZmZ d dlZd dl	Z	d dl
m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eee   f   fdZ	 dded	ed
   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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   fdZdedee   fdZ 	 d!dee   d	ed
   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)uuid)Batch)	CallTypesModelResponseUsage)token_counterfile_content_dictionarycustom_llm_provider)openaiazure	vertex_ai
model_namereturnc                 d   K   t        || |      }t        | ||      }t        | |      }|||fS w)z1
    Calculate the cost and usage of a batch
    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   
batch_costbatch_usagebatch_modelss         t/Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/litellm/batches/batch_utils.pycalculate_batch_cost_and_usager       sM      (/ 7J
 ? 7/K
 77NPZ[L{L00s   .0batchc                    K   t        | |       d{   }t        |||      }t        |||      }t        ||      }|||fS 7 1w)z?Helper function to process a completed batch and handle loggingNr   r   ),_get_batch_output_file_content_as_dictionaryr   r   r   )r!   r   r   r   r   r   r   s          r   _handle_completed_batchr$   &   sk      %Q"% 
 (/ 7J
 ? 7/K 77NPZ[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   B   sY     |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   total_cost=%s)(calculate_vertex_ai_batch_cost_and_usager   debug%_get_batch_job_cost_from_file_content)r   r   r   r   _
total_costs         r   r   r   U   sa     k)j@AXZde
A6
C 7 7/J *5r.   vertex_ai_batch_responsesc                 4   ddl m} ddlm} d}d}d}d}| D ]o  }|j	                  d      dk(  st               }	|xs d}
 ||
dd	d
gdt        j                  t        j                         dt        t        j                               z   dt        t        j                               di i	      }i |_        t        j                  d      } |       j                  |d   |	|
||      }t!        j"                  |dt        j                  j$                        }||z  }t'        |dd      }|r|}n)t)        |d      r|j+                         ni }t-        |      }||j.                  z  }||j0                  z  }||j2                  z  }r |t5        |||      fS )zF
    Calculate both cost and usage from Vertex AI batch responses
    r   )Logging)VertexGeminiConfig        statusJOB_STATE_SUCCEEDEDzgemini-2.5-flashuserbatch_request)rolecontentFbatch_batch_processingoptional_params)	r&   messagesstream	call_type
start_timelitellm_call_idfunction_idlitellm_trace_idkwargs   response)completion_responsemodel_responser&   logging_objraw_responser   rN   r   rF   usageNdicttotal_tokensprompt_tokenscompletion_tokens)*litellm.litellm_core_utils.litellm_loggingr8   @litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_geminir9   r)   r   r   aretrieve_batchtimestrr	   uuid4rC   httpxResponse;_transform_google_generate_content_to_openai_model_responselitellmcompletion_costvaluegetattrhasattrrT   '_get_batch_job_usage_from_response_bodyrV   rW   rX   r   )r6   r   r8   r9   r5   rV   rW   rX   rM   rO   actual_model_namerP   rQ   openai_format_responsecost	usage_objrS   response_dicts                     r   r1   r1   l   s    C JLM-<<!%:: +_N !+ @.@ "'#)oFG#3399; (3tzz|+< <.!$TZZ\!2)2.
K +-K' >>#.L%7%9%u%u$,Z$8-'') &v &" **$:$/#3399D
 $J   6FI! BII_agAh 6 ; ; =np?NE...LU000M!8!88m .p u!#+  r.   c                    K   ddl m} |dk(  rt        d      | j                  t        d       || j                  |       d{   }t	        |j
                        S 7 w)zE
    Get the batch output file content as a list of dictionaries
    r   )afile_contentr   z1Vertex AI does not support file content retrievalNz3Output file id is None cannot retrieve file content)file_idr   )litellm.files.mainrn   
ValueErroroutput_file_id_get_file_content_as_dictionaryr@   )r!   r   rn   _file_contents       r   r#   r#      sj      1k)LMM#NOO'$$/ M +=+@+@AA	s   AA#A!A#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stripsplitr*   jsonloadsr   r2   dumps	Exception)ru   _file_content_strjson_objectslinees        r   rs   rs      s    
(//8%++-33D9D##DJJt$45 : 	.

<PQ0RS s   7B AB 	BBBc                    	 d}t        j                  dt        j                  | d             | D ]b  }t	        |      st        |      }|t        j                  ||t        j                  j                        z  }t        j                  d|       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:   zfile_content_dictionary=%srx   ry   rR   r0   z.error in _get_batch_job_cost_from_file_contentN)r   r2   r~   r   r'   r(   rb   rc   r   r[   rd   r   error)r   r   r5   r+   r,   r   s         r   r3   r3      s    
($**5LUV*W	
 -E-e4!I%!Pg55(6(;'77== 

 $$_jA -  MqQs   =B  AB 	B>!B99B>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   rU   )r1   r'   r(   rg   rV   rW   rX   r   )r   r   r   r4   r   rV   rW   rX   r+   r,   rS   s              r   r   r      s     k)jABY[ef; LM()%0EeLNB>REE...LU000M!8!88 ) !#+ 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&    rD   )r&   rD   rU   )r)   r   r   )
r   r   r   rW   rX   r+   r   r&   rD   item_tokenss
             r   _get_batch_job_input_file_usager     s     M(yy$*"2388J+'ehGK[(M ) "%66#+ r.   response_bodyc                 H    | j                  dd      xs i }t        di |}|S )z>
    Get the tokens of a batch job from the response body
    rS   N )r)   r   )r   _usage_dictrS   s      r   rg   rg   8  s-      ##GT28bK';'ELr.   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
    rM   Nr   r)   )r   	_responser,   s      r   r(   r(   A  s6     ,//
DAGRI]]6406BNr.   c                 X    | j                  dd      xs i }|j                  dd      dk(  S )z7
    Check if the batch job response status == 200
    rM   Nstatus_coderL   r   )r   r   s     r   r'   r'   J  s1     ,//
DAGRI==-44r.   )N)r   N)r   )(r~   r\   typingr   r   r   r   r   r_   rb   litellm._loggingr   litellm._uuidr	   litellm.types.llms.openair
   litellm.types.utilsr   r   r   litellm.utilsr   rT   r]   floatr    r$   r   r   r1   r#   bytesrs   r3   r   r   rg   r(   boolr'   r   r.   r   <module>r      s     6 6   +  + ? ? ' !%1!$Z1 !?@1 1 5%c"#	14 !%11 !?@1 1 5%c"#	1< !%!$Z 
#Y* DL $!$Z !?@  	2 !%L#DzLL 5%<Lb DLBB !?@B 
$ZB,% DJ & DL!$Z !?@ < DL $!$Z !?@  	@ DL $!$Z !?@  	84 E D S 5$ 54 5r.   