
    g'                     r   d dl Z d dlZd dlZd dlZd dlmZmZmZmZ d dl	Z	d dl
mZ d dlmZmZ d dlmZ d dlmZ d dlmZ d dlmZmZ 	 	 d&d	ed
ed   dee   fdZded
ed   dedej                  dej                  ddfdZdedededej                  dej                  ddfdZ	 d'dee   d
ed   de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fdZ$dedefdZ%dedefd Z&dede'fd!Z(d"edej                  dej                  ded#ed$edefd%Z)y)(    N)AnyListLiteralOptional)verbose_logger)"BATCH_STATUS_POLL_INTERVAL_SECONDSBATCH_STATUS_POLL_MAX_ATTEMPTS)afile_content)Logging)Batch)StandardLoggingPayloadUsagebatch_idcustom_llm_provider)openaiazure	vertex_ailogging_objc           
      z  K   ddl m} t        j                  d       |t	        d      t        t              D ]  }	 t        j                  j                         } || |       d{   }t        j                  d|j                         |j                  dk(  r9t        j                  j                         }t        d|||||d| d{     y|j                  d	k(  r	 t        j                  t               d{     y7 7 <# t        $ r }	t        j                  d
|	       Y d}	~	Ld}	~	ww xY w7 7w)z
    Async Job waits for the batch to complete and then logs the completed batch usage - cost, total tokens, prompt tokens, completion tokens


    Polls retrieve_batch until it returns a batch with status "completed" or "failed"
       )aretrieve_batchzF.....in _batches_async_logging... polling retrieve to get batch statusNzDlogging_obj is None cannot calculate cost / log batch creation eventz-in _batches_async_logging... batch status= %s	completed)batchr   r   
start_timeend_timefailedzerror in batches_async_logging )mainr   r   debug
ValueErrorranger	   datetimenowstatus_handle_completed_batch	Exceptionerrorasynciosleepr   )
r   r   r   kwargsr   _r   r   r   es
             P/var/www/openai/venv/lib/python3.12/site-packages/litellm/batches/batch_utils.pybatches_async_loggingr.      s9     &P R
 	
 12	F!**..0J!0;N!OOE  ? ||{*#,,002- (; +)%    ) mm>???/ 3 P  	F  !A1EE	F?sk   ;D;*D(D	)A%DDDD;D%D;D9D;	DD	D6D1,D;1D66D;r   r   r   returnc           	         K   t        | |       d{   }t        ||       d{   }t        ||      }t        d|||||d| d{    y7 @7 -7 	w)z?Helper function to process a completed batch and handle loggingN)r   file_content_dictionaryr1   r   )r   batch_usage
batch_costr   r   r   ),_get_batch_output_file_content_as_dictionary_batch_cost_calculator,_get_batch_job_total_usage_from_file_content_log_completed_batch)	r   r   r   r   r   r*   r1   r4   r3   s	            r-   r%   r%   B   s      %Q"% 
 ./ 7 J ? 7/K     
s1   AAAA%AAAAAr3   r4   c                   K   d| _         t        |||| ||      }|| j                  d<   t        j                  | j                  d||d             t        j                  | j                  d||f      j                          yw)zFHelper function to handle all logging operations for a completed batchbatch_success)r*   r   r   r   batch_usage_objectresponse_coststandard_logging_objectN)resultr   r   	cache_hit)targetargs)
	call_type3_create_standard_logging_object_for_completed_batchmodel_call_detailsr(   create_taskasync_success_handler	threadingThreadsuccess_handlerstart)r   r3   r4   r   r   r*   r=   s          r-   r8   r8   e   s      ,KQ&  AXK""#<= ))!	 	* 	
 **J) egs   BBr1   c                 t   K   |dk(  rt        d      t        | |      }t        j                  d|       |S w)zC
    Calculate the cost of a batch based on the output file id
    r   1Vertex AI does not support file content retrievalr2   total_cost=%s)r    %_get_batch_job_cost_from_file_contentr   r   )r1   r   
total_costs      r-   r6   r6      sD      k)LMM6 7/J *5s   68c                    K   |dk(  rt        d      | j                  t        d      t        | j                  |       d{   }t        |j                        S 7 w)zE
    Get the batch output file content as a list of dictionaries
    r   rL   Nz3Output file id is None cannot retrieve file content)file_idr   )r    output_file_idr
   _get_file_content_as_dictionarycontent)r   r   _file_contents      r-   r5   r5      sg      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splitappendjsonloadsr   r   dumpsr&   )rV   _file_content_strjson_objectsliner,   s        r-   rS   rS      s    
(//8%++-33D9D##DJJt$45 : 	.

<PQ0RS s   7B AB 	BBBc                 P   	 d}t        j                  dt        j                  | d             | D ]I  }t	        |      st        |      }|t        j                  ||      z  }t        j                  d|       K |S # t        $ r}t        j                  d|       |d}~ww xY w)	z;
    Get the cost of a batch job from the file content
    g        zfile_content_dictionary=%srY   rZ   )completion_responser   rM   z.error in _get_batch_job_cost_from_file_contentN)
r   r   r`   rb   _batch_response_was_successful(_get_response_from_batch_job_output_filelitellmcompletion_costr&   r'   )r1   r   rO   _item_response_bodyr,   s         r-   rN   rN      s    
($**5LUV*W	
 -E-e4!I%!Pg55(6(; 
 $$_jA -  MqQs   =A?  >A? ?	B%B  B%c                     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   )total_tokensprompt_tokenscompletion_tokens)rh   ri   '_get_batch_job_usage_from_response_bodyro   rp   rq   r   )r1   r   ro   rp   rq   rl   rm   usages           r-   r7   r7      s     LM()%0EeLNB>REE...LU000M!8!88 ) !#+     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   Nr   )getr   )ru   _usage_dictrs   s      r-   rr   rr      s-      ##GT28bK';'ELrt   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
    responseNbodyrw   )ry   	_responserm   s      r-   ri   ri      s6     ,//
DAGRI]]6406BNrt   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}   )ry   r~   s     r-   rh   rh     s1     ,//
DAGRI==-44rt   r*   r;   r<   c                     |j                   j                  dd      }|t        d      d|d<   ||d<   |j                  |d<   |j                  |d<   |j
                  |d	<   |S )
z@
    Create a standard logging object for a completed batch
    r=   Nz<unable to create standard logging object for completed batchr:   rB   r<   ro   rp   rq   )rD   rw   r    ro   rp   rq   )r*   r   r   r   r;   r<   r=   s          r-   rC   rC     s     *<<@@!4 &WXX ,;K(/<O,.@.M.MN+/A/O/OO,3E3W3W/0""rt   )r   N)r   )*r(   r"   r`   rG   typingr   r   r   r   rj   litellm._loggingr   litellm.constantsr   r	   litellm.files.mainr
   *litellm.litellm_core_utils.litellm_loggingr   LiteLLMLoggingObjlitellm.types.llms.openair   litellm.types.utilsr   r   strr.   r%   floatr8   dictr6   r5   bytesrS   rN   r7   rr   ri   boolrh   rC   r   rt   r-   <module>r      sk       / /  + - S + =
 DL/3,@,@ !?@,@ +,,@^   !?@  #  !!	 
   
 F"""" " !!	"
 " 
"N DL!$Z !?@ & DLBB !?@B 
$ZB(% DJ & DL!$Z !?@ : DL!$Z !?@ 04 E D S 5$ 54 5##!!# # #	#
 # # #rt   