o
    ưi:                     @   s  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 		d1dee ded	 d
ee dee deeeee f f
ddZ		d1deded	 d
ee dee deeeee f f
ddZ	d2dee d
ee dee fddZ			d3dee ded	 d
ee dee def
ddZ	d2dee d
ee deeef fddZ		d4deded	 dee dee fddZdee defddZdedee fd d!Z		d4dee ded	 dee defd"d#Z		d4dee ded	 d
ee defd$d%Z		d4dee ded& d
ee defd'd(Z d)edefd*d+Z!d,edefd-d.Z"d,ede#fd/d0Z$dS )5    N)AnyListLiteralOptionalTuple)verbose_logger)Batch)	CallTypes	ModelInfoUsage)token_counterfile_content_dictionarycustom_llm_provider)openaiazure	vertex_aiZhosted_vllmZ	anthropic
model_name
model_inforeturnc                    s4   t || ||d}t| ||d}t| |}|||fS )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_models r   R/home/app/Keep/.python/lib/python3.10/site-packages/litellm/batches/batch_utils.pycalculate_batch_cost_and_usage   s   

r   batchlitellm_paramsc                    sF   t | ||dI dH }t|||d}t|||d}t||}|||fS )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   r   r   r   _handle_completed_batch*   s    

r"   c                 C   sD   |r|gS g }| D ]}t |rt|}|d}|r|| q	|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_modelr   r   r   r   N   s   

r   r   c                 C   sH   |dkr|rt | |\}}td| |S t| ||d}t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_costr   r   r   r   a   s   
r   vertex_ai_batch_responsesc                 C   s$  ddl m} d}d}d}d}|pd}| D ]k}|d}	|	du r q|	di }
|
ddp-d}|
d	dp5d}|
d
dp?|| }t|||d}z|||dd\}}||| 7 }W n tyr } ztdt| W Y d}~nd}~ww ||7 }||7 }||7 }qtd|||| |t|||dfS )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responseNZusageMetadataZpromptTokenCountZcandidatesTokenCountZ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r8   r6   r7   )	litellm.cost_calculatorr3   r&   r   	Exceptionr   r-   strinfo)r1   r   r3   r0   r8   r6   r7   Zactual_model_namer5   response_bodyZusage_metadataZ_promptZ_completionZ_totalZ
line_usageZp_costZc_coster   r   r   r,   z   sX   


r,   c              
      s   ddl m} ddlm} |dkrtd| jdu rtd| j}||}|r^z|dd	 d
d }td|  W n  t	t
fy] } ztd| j d|  W Y d}~nd}~ww ||d}t|}	||	 |di |I dH }
t|
jS )a^  
    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   r   )Zlitellm.files.mainrA   Z1litellm.proxy.openai_files_endpoints.common_utilsrB   
ValueErrorZoutput_file_idsplitr   r-   
IndexErrorAttributeErrorerror _extract_file_access_credentialsupdate_get_file_content_as_dictionarycontent)r   r   r    rA   rB   rE   Zis_base64_unified_file_idr@   Zfile_content_kwargscredentialsZ_file_contentr   r   r   r!      s0   
$

r!   c                 C   s2   i }| rg d}|D ]}|| v r| | ||< q
|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
    )Zapi_keyZapi_baseapi_versionZorganizationZazure_ad_tokenZazure_ad_token_providerZvertex_projectZvertex_locationZvertex_credentialstimeoutmax_retriesr   )r    rO   Zcredential_keyskeyr   r   r   rK      s   rK   file_contentc              
   C   sp   z)|  d}g }| dD ]}|r|t| qtdtj|dd |W S  t	y7 } z|d}~ww )zO
    Get the file content as a list of dictionaries from JSON Lines format
    zutf-8
zjson_objects=%s   indentN)
decodestriprG   r'   jsonloadsr   r-   dumpsr<   )rT   Z_file_content_strZjson_objectsliner@   r   r   r   rM     s   
rM   c              
   C   s   ddl m} zNd}tdtj| dd | D ];}t|rQt|}|dur?t|}|	dd	}|||||d
\}	}
||	|
 7 }n|t
j||tjjd7 }td| q|W S  tyh } ztd| |d}~ww )z;
    Get the cost of a batch job from the file content
    r   r2   r4   zfile_content_dictionary=%srV   rW   Nr#    )r9   r#   r   r   )Zcompletion_responser   Z	call_typer+   z.error in _get_batch_job_cost_from_file_content)r;   r3   r   r-   r[   r]   r$   r%   '_get_batch_job_usage_from_response_bodyr&   litellmcompletion_costr	   Zaretrieve_batchvaluer<   rJ   )r   r   r   r3   r0   r(   r)   r9   r#   Zprompt_costrb   r@   r   r   r   r.     s@   
r.   c                 C   sx   |dkr|rt | |\}}|S d}d}d}| D ]}t|r4t|}	t|	}
||
j7 }||
j7 }||
j7 }qt|||dS )z=
    Get the tokens of a batch job from the file content
    r   r   r:   )r,   r$   r%   r`   r8   r6   r7   r   )r   r   r   r/   r   r8   r6   r7   r(   r)   r9   r   r   r   r   B  s&   	


r   )r   r   r   c           
      C   sd   d}d}| D ]"}| di }| d|pd}| dg }|r(t||d}	||	7 }qt|| ||d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#   re   r:   )r&   r   r   )
r   r   r   r6   r7   r(   rd   r#   re   Zitem_tokensr   r   r   _get_batch_job_input_file_usage`  s   
rf   r?   c                 C   s"   |  ddpi }tdi |}|S )z>
    Get the tokens of a batch job from the response body
    r9   Nr   )r&   r   )r?   Z_usage_dictr9   r   r   r   r`   |  s   r`   batch_job_output_filec                 C   s$   |  ddpi }| ddpi }|S )z9
    Get the response from the batch job output file
    r5   Nrd   r&   )rg   	_responser)   r   r   r   r%     s   r%   c                 C   s    |  ddpi }| dddkS )z7
    Check if the batch job response status == 200
    r5   Nstatus_code   rh   )rg   ri   r   r   r   r$     s   r$   )NN)N)r   NN)r   N)%r[   typingr   r   r   r   r   ra   Zlitellm._loggingr   Zlitellm.types.llms.openair   Zlitellm.types.utilsr	   r
   r   Zlitellm.utilsr   dictr=   floatr   r"   r   r   r,   r!   rK   bytesrM   r.   r   rf   r`   r%   boolr$   r   r   r   r   <module>   s    
"
&



B
/
,
 
		