o
    ưil                     @   s   d Z ddlmZ ddlmZmZmZ ddlmZm	Z	 ddl
mZ eG dd dZde	d	efd
dZ	ddedee dedee d	ef
ddZdededeee  d	efddZdededeee  d	efddZdede	d	eeef fddZdS )zc
Cost calculator for Dashscope Chat models. 

Handles tiered pricing and prompt caching scenarios.
    )	dataclass)ListOptionalTuple)	ModelInfoUsage)get_model_infoc                   @   s2   e Zd ZU dZeed< eed< eed< eed< dS )TokenBreakdownz%Token breakdown for cost calculation.text_tokenscached_tokenscompletion_tokensreasoning_tokensN)__name__
__module____qualname____doc__int__annotations__ r   r   ]/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/dashscope/cost_calculator.pyr	      s   
 r	   usagereturnc                 C   st   d}| j rt| j dr| j jpd}| j| }d}t| dr,| jr,t| jdr,| jjp+d}| jp0d| }t||||S )zFExtract token counts from usage, handling cached and reasoning tokens.r   r   completion_tokens_detailsr   )Zprompt_tokens_detailshasattrr   Zprompt_tokensr   r   r   r	   )r   r   r
   r   r   r   r   r   _extract_token_breakdown   s$   

r   Ntokenstiered_pricingcost_keyfallback_cost_keyc                 C   s   |r| dkrdS d}d}t |dd d}|D ]C}|| kr n<|dg }t|dkr+q|\}	}
| |	kr4qt|	|}t|
| }||krY|| }||pP||d}||| 7 }|}q|| k ry|ry|d }| | }||pr||d}||| 7 }|S )	a  
    Calculate cost for a given number of tokens based on a true tiered pricing structure.

    This function iterates through sorted pricing tiers, calculates the cost for the
    number of tokens that fall into each tier's range, and sums them up to get the total cost.

    Args:
        tokens (int): The total number of tokens to calculate the cost for.
        tiered_pricing (List[dict]): A list of dictionaries, where each dictionary
            represents a pricing tier.
        cost_key (str): The key in the tier dictionary that holds the per-token cost
            (e.g., 'input_cost_per_token').
        fallback_cost_key (Optional[str], optional): A fallback key to use if the
            primary `cost_key` is not found in a tier. Defaults to None.

    Returns:
        float: The total calculated cost for the given tokens.

    Example:
        >>> tiered_pricing = [
        ...     {"range": [0, 100000], "input_cost_per_token": 0.0001},
        ...     {"range": [100000, 500000], "input_cost_per_token": 0.00005},
        ... ]

        Calculating cost for 150,000 tokens:
        (100,000 * 0.0001) + (50,000 * 0.00005) = $12.5
    r           c                 S   s   |  dddgd S )Nranger   )get)xr   r   r   <lambda>X   s    z(_calculate_tiered_cost.<locals>.<lambda>)keyr       )sortedr!   lenmaxmin)r   r   r   r   Z
total_costZtokens_processedZsorted_tiersZtierZ
tier_rangeZrange_startZ	range_endZ
tier_startZtier_endZtokens_in_tiercost_per_tokenZ	last_tierZremaining_tokensr   r   r   _calculate_tiered_cost1   s8   !

r,   	breakdown
model_infoc                 C   t   |rt | j|dd}t | j|ddd}|| S t|dpd}|d}|du r,|}nt|}| j| | j|  S )z4Calculate total prompt cost including cached tokens.Zinput_cost_per_tokenr   r   r   Zcache_read_input_token_costr   r   r   r   r   N)r,   r
   r   floatr!   )r-   r.   r   Z	text_costZ
cache_costZ
input_costZcache_cost_valr   r   r   _calculate_prompt_cost{   s&   
r3   c                 C   r/   )z;Calculate total completion cost including reasoning tokens.Zoutput_cost_per_tokenr0   Zoutput_cost_per_reasoning_tokenr1   r   N)r,   r   r   r2   r!   )r-   r.   r   completion_costZreasoning_costZoutput_costZreasoning_cost_valr   r   r   _calculate_completion_cost   s*   
r5   modelc                 C   sV   t | dd}t|}t|dtr|dnd}t|||d}t|||d}||fS )a>  
    Calculate cost per token for Dashscope models.

    Supports both tiered and flat pricing with cached and reasoning tokens.

    Args:
        model: Model name without provider prefix
        usage: LiteLLM Usage block

    Returns:
        Tuple[float, float] - (prompt_cost_in_usd, completion_cost_in_usd)
    Z	dashscope)r6   Zcustom_llm_providerr   N)r-   r.   r   )r   r   
isinstancer!   listr3   r5   )r6   r   r.   r-   r   Zprompt_costr4   r   r   r   r+      s   r+   )N)r   dataclassesr   typingr   r   r   Zlitellm.types.utilsr   r   Zlitellm.utilsr   r	   r   r   dictstrr2   r,   r3   r5   r+   r   r   r   r   <module>   sN    	
J

 

""