
    i,                         d dl Z d dlZd dlmZmZmZmZmZmZm	Z	m
Z
 d dlZd dlmZmZ d dlmZ d dlmZ d dlmZmZ d dlmZmZmZ er	d dlmZ eZneZ G d	 d
e      Zy)    N)TYPE_CHECKINGAnyDictListLiteralOptionalUnioncast)HeadersResponse)BaseBatchesConfig)BaseLLMException)AllMessageValuesCreateBatchRequest)LiteLLMBatchLlmProvidersModelResponse)Loggingc                      e Zd Zd Zedefd       Z	 	 d!dedede	e
   ded	ed
ee   dee   defdZdee   d
ee   deded	ededefdZdededed	edeeeeeef   f   f
dZdee   dej*                  ded	edef
dZdee   deded	edef
dZdeded	edeeeeeef   f   fdZdee   dej*                  ded	edef
dZdededeeef   ddfdZ	 	 d!dededededede	e
   ded	eded
ee   dee    defd Z!y)"AnthropicBatchesConfigc                 L    ddl m} ddlm}  |       | _         |       | _        y )N   )AnthropicConfig)AnthropicModelInfo)chat.transformationr   common_utilsr   anthropic_chat_configanthropic_model_info)selfr   r   s      ~/Users/manta/Documents/Projects/TheRoad-I1/.venv/lib/python3.12/site-packages/litellm/llms/anthropic/batches/transformation.py__init__zAnthropicBatchesConfig.__init__   s    95%4%6"$6$8!    returnc                 "    t         j                  S )z4Return the LLM provider type for this configuration.)r   	ANTHROPIC)r   s    r    custom_llm_providerz*AnthropicBatchesConfig.custom_llm_provider   s     %%%r"   Nheadersmodelmessagesoptional_paramslitellm_paramsapi_keyapi_basec                     | j                   j                  |      }|t        d      dddd}	|	j                  |       d|vrd|d<   |j                  |	       |S )zAValidate and prepare environment-specific headers and parameters.zMissing Anthropic API Key - A call is being made to anthropic but no key is set either in the environment variables or via paramszapplication/jsonz
2023-06-01)acceptzanthropic-versionzcontent-typezanthropic-betazmessage-batches-2024-09-24)r   get_auth_header
ValueErrorupdate)
r   r'   r(   r)   r*   r+   r,   r-   auth_header_headerss
             r    validate_environmentz+AnthropicBatchesConfig.validate_environment"   sw     //??H T  )!-.

 	$7*(DG$%x r"   datac                     |xs | j                   j                  |      }|j                  d      s|j                  d       d}|S )z0Get the complete URL for batch creation request.z/v1/messages/batches/)r   get_api_baseendswithrstrip)r   r-   r,   r(   r*   r+   r6   s          r    get_complete_batch_urlz-AnthropicBatchesConfig.get_complete_batch_url>   sJ     Ot88EEhO  !78"//#.//CDHr"   create_batch_datac                     t        d      )z
        Transform the batch creation request to Anthropic format.

        Not currently implemented - placeholder to satisfy abstract base class.
        0Batch creation not yet implemented for AnthropicNotImplementedError)r   r(   r=   r*   r+   s        r    transform_create_batch_requestz5AnthropicBatchesConfig.transform_create_batch_requestM        ""TUUr"   raw_responselogging_objc                     t        d      )z
        Transform Anthropic MessageBatch creation response to LiteLLM format.

        Not currently implemented - placeholder to satisfy abstract base class.
        r?   r@   )r   r(   rD   rE   r+   s        r    transform_create_batch_responsez6AnthropicBatchesConfig.transform_create_batch_response[   rC   r"   batch_idc                 l    |xs | j                   j                  |      }|j                  d       d| S )a  
        Get the complete URL for batch retrieval request.

        Args:
            api_base: Base API URL (optional, will use default if not provided)
            batch_id: Batch ID to retrieve
            optional_params: Optional parameters
            litellm_params: LiteLLM parameters

        Returns:
            Complete URL for Anthropic batch retrieval: {api_base}/v1/messages/batches/{batch_id}
        r8   z/v1/messages/batches/)r   r9   r;   )r   r-   rH   r*   r+   s        r    get_retrieve_batch_urlz-AnthropicBatchesConfig.get_retrieve_batch_urli   s;    & Ot88EEhO//#&''<XJGGr"   c                     i S )z
        Transform batch retrieval request for Anthropic.

        For Anthropic, the URL is constructed by get_retrieve_batch_url(),
        so this method returns an empty dict (no additional request params needed).
         )r   rH   r*   r+   s       r     transform_retrieve_batch_requestz7AnthropicBatchesConfig.transform_retrieve_batch_request   s	     	r"   c                 J   	 |j                         }|j                  dd      }|j                  dd      }dddd	}	|	j                  |d      }
d
t        t
           dt        t           fd} ||j                  d            } ||j                  d            } ||j                  d            } ||j                  d            } ||j                  d            }|j                  di       }ddlm}  |t        |j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  dd      g      |j                  dd      |j                  dd            }t        d1i d|ddddddd d!d"d#d$|
d%|d&dd|xs t        t        j                               d'|dk(  r|ndd|d(dd)|d*k(  r|ndd+dd,|r|ndd-|d.k(  r|ndd/|d.k(  r|r|ndd|d0i S # t        $ r}t        d|       d}~ww xY w)2zFTransform Anthropic MessageBatch retrieval response to LiteLLM format.z*Failed to parse Anthropic batch response: Nid processing_statusin_progress
cancelling	completed)rR   	cancelingendedts_strr#   c                     | sy 	 ddl m } |j                  | j                  dd            }t        |j	                               S # t
        $ r Y y w xY w)Nr   )datetimeZz+00:00)rY   fromisoformatreplaceint	timestamp	Exception)rW   rY   dts      r    parse_timestampzQAnthropicBatchesConfig.transform_retrieve_batch_response.<locals>.parse_timestamp   sN    -++FNN3,IJ2<<>** s   ?A 	AA
created_atended_at
expires_atcancel_initiated_atarchived_atrequest_countsr   )BatchRequestCounts
processing	succeedederroredcanceledexpired)totalrT   failedobjectbatchendpointz/v1/messageserrorsinput_file_idNonecompletion_window24hstatusoutput_file_iderror_file_idin_progress_atfinalizing_atcompleted_atrV   	failed_at
expired_atcancelling_atrU   cancelled_atmetadatarL   )jsonr_   r1   getr   strr]   openai.types.batchrh   sumr   time)r   r(   rD   rE   r+   response_dataerH   rQ   status_mappingopenai_statusra   rb   rc   rd   re   rf   request_counts_datarh   rg   s                       r    !transform_retrieve_batch_responsez8AnthropicBatchesConfig.transform_retrieve_batch_response   s   	O(--/M
 !$$T2.)--.A=Q  )% 
 	" '**+<mL		HSM 		hsm 		 %]%6%6|%DE
"=#4#4Z#@A$]%6%6|%DE
-m.?.?@U.VW%m&7&7&FG ,//0@"E9+'++L!<'++K;'++Iq9'++J:'++Iq9 *--k1=&**9a8
  


 $
 	

 !
 $
 !
 $
 
 "5S%5
 *;m)K:QU
 "
 
 &7'%At
 
  '2{t!
$ !K/ .'
* !K/H "-
. */
0 1
 	
  	OI!MNN	Os   H 	H"HH"error_messagestatus_coder   c                     ddl m} t        |t              rt	        |      }nt        |t              r|nd} ||||      S )z.Get the appropriate error class for Anthropic.r   )AnthropicErrorN)r   messager'   )r   r   
isinstancedictr   )r   r   r   r'   r   headers_objs         r    get_error_classz&AnthropicBatchesConfig.get_error_class   sA     	2 gt$-4W-=K%/%A'tK#]K
 	
r"   model_responserequest_dataencoding	json_modec                    ddl m} ddlm} |j                  j                         }g }	 |j                  d      }|D ]{  }|j                         }|s	 t        j                  |      }|d   d   }| j                  j                  |||      }t        |dd       }|r|j                  t        ||             } |j                  |      }t!        |d|       |S # t        j                  $ r Y w xY w# t"        $ r}|d }~ww xY w)	Nr   )BaseTokenUsageProcessor)Usage
resultr   )completion_responserD   r   usage)litellm.cost_calculatorr   litellm.types.utilsr   textstripsplitr   loadsr   transform_parsed_responsegetattrappendr
   JSONDecodeErrorcombine_usage_objectssetattrr_   )r   r(   rD   r   rE   r   r)   r*   r+   r   r,   r   r   r   response_text	all_usagelineslineresponse_jsonr   transformed_responsetransformed_response_usagecombined_usager   s                           r    transform_responsez)AnthropicBatchesConfig.transform_response  s#    	D-$))//1!#	!	!''-Ezz|$(JJt$4M*7*A)*L'22LL0C)5+9 M  ) 29,gt2. 2!((e5O)PQ) 2 5JJ9UNNG^<!! ++   	G	s<   )C4 A%C9!C4 C1.C4 0C11C4 4	D=C??D)NN)"__name__
__module____qualname__r!   propertyr   r&   r   r   r   r   r   r5   r   r   r<   r	   bytesr   rB   httpxr   LoggingClassr   rG   rJ   rM   r   r]   r   r   r   boolr   rL   r"   r    r   r      s   9 &\ & & "&"&  '(	
   # 3- 
83- # 	
   ! 
VV .V 	V
 V 
uc4S>)	*VV}V nnV "	V
 V 
VH3-H H 	H
 H 
H,  	
 
uc4S>)	*b
}b
 nnb
 "	b

 b
 
b
H
 
/2
=B4==Q
	
6 "&$(55 5 &	5
 "5 5 '(5 5 5 5 #5 D>5 
5r"   r   )r   r   typingr   r   r   r   r   r   r	   r
   r   r   r   ,litellm.llms.base_llm.batches.transformationr   )litellm.llms.base_llm.chat.transformationr   litellm.types.llms.openair   r   r   r   r   r   *litellm.litellm_core_utils.litellm_loggingr   LiteLLMLoggingObjr   r   rL   r"   r    <module>r      sH      Q Q Q  # J F J I IW$LLb. br"   