o
    ưij7                  	   @   s   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	Z	d dl
m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mZmZ d dlmZmZmZ d	d
lmZ d	dlmZ dddddddddZ G dd dZ!dS )    N)Any	CoroutineOptionalUnion)verbose_logger)uuid)get_async_httpx_client)Logging)FileContentRequestHttpxBinaryResponseContentOpenAIBatchResultOpenAIChatCompletionResponseOpenAIErrorBody)	CallTypesLlmProvidersModelResponse   )AnthropicConfig)AnthropicModelInfo  i  i  i  i    i  i  )invalid_request_errorZauthentication_errorZpermission_errorZnot_found_errorZrate_limit_error	api_errorZoverloaded_errorZtimeout_errorc                   @   s   e Zd ZdZdd Z				ddedee dee d	ee	e
jf d
ee defddZ				ddededee dee d	ee	e
jf d
ee deeeeeef f fddZdedefddZdededefddZdS )AnthropicFilesHandlerz
    Handles Anthropic Files API operations.
    
    Currently supports:
    - file_content() for retrieving Anthropic Message Batch results
    c                 C   s   t  | _d S )N)r   anthropic_model_info)self r   [/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/anthropic/files/handler.py__init__0   s   zAnthropicFilesHandler.__init__N     @file_content_requestapi_baseapi_keytimeoutmax_retriesreturnc                    s   | d}|std|dr|ddd}n|}| j|}|p'| j }|s.td|d d| d	}d
d|d}	tt	j
d}
|
j ||	dI dH }|  | |j}tj|j|j||jd}t|dS )as  
        Async: Retrieve file content from Anthropic.
        
        For batch results, the file_id should be the batch_id.
        This will call Anthropic's /v1/messages/batches/{batch_id}/results endpoint.
        
        Args:
            file_content_request: Contains file_id (batch_id for batch results)
            api_base: Anthropic API base URL
            api_key: Anthropic API key
            timeout: Request timeout
            max_retries: Max retry attempts (unused for now)
            
        Returns:
            HttpxBinaryResponseContent: Binary content wrapped in compatible response format
        file_idz+file_id is required in file_content_requestzanthropic_batch_results:    zMissing Anthropic API Key/z/v1/messages/batches/z/resultszapplication/jsonz
2023-06-01)acceptzanthropic-versionz	x-api-key)Zllm_provider)urlheadersN)status_coder,   contentrequest)response)get
ValueError
startswithreplacer   Zget_api_baseZget_api_keyrstripr   r   Z	ANTHROPICraise_for_status3_transform_anthropic_batch_results_to_openai_formatr.   httpxResponser-   r,   r/   r   )r   r    r!   r"   r#   r$   r&   Zbatch_idZresults_urlr,   Zasync_clientZanthropic_responsetransformed_contenttransformed_responser   r   r   afile_content3   s@   


z#AnthropicFilesHandler.afile_content	_is_asyncc              	   C   s0   |r| j ||||dS t| j |||||dS )a  
        Retrieve file content from Anthropic.
        
        For batch results, the file_id should be the batch_id.
        This will call Anthropic's /v1/messages/batches/{batch_id}/results endpoint.
        
        Args:
            _is_async: Whether to run asynchronously
            file_content_request: Contains file_id (batch_id for batch results)
            api_base: Anthropic API base URL
            api_key: Anthropic API key
            timeout: Request timeout
            max_retries: Max retry attempts (unused for now)
            
        Returns:
            HttpxBinaryResponseContent or Coroutine: Binary content wrapped in compatible response format
        )r    r!   r"   r$   )r    r!   r"   r#   r$   )r<   asynciorun)r   r=   r    r!   r"   r#   r$   r   r   r   file_content   s    z"AnthropicFilesHandler.file_contentanthropic_contentc              
   C   s  zt  }g }|d}| dD ]}| sqt|}|dd}|di }|dd}	|	dkrY|di }
|
rX| j|
|d	}|d
|
dd|dd}|t	| q|	dkr|di }|di }|dd}|dd}t
|d}d||di}|||dd|dd}|t	| q|	dv rdd|	 ddi}|dd|dd}|t	| qd|}|r|d7 }|dW S  ty } ztd|  |W  Y d}~S d}~ww )a(  
        Transform Anthropic batch results JSONL to OpenAI batch results JSONL format.
        
        Anthropic format:
        {
          "custom_id": "...",
          "result": {
            "type": "succeeded",
            "message": { ... }  // Anthropic message format
          }
        }
        
        OpenAI format:
        {
          "custom_id": "...",
          "response": {
            "status_code": 200,
            "request_id": "...",
            "body": { ... }  // OpenAI chat completion format
          }
        }
        utf-8
	custom_idr'   resulttypeZ	succeededmessage)anthropic_messageanthropic_config   id)r-   
request_idbody)rD   r0   ZerrorederrorzUnknown errorr   r   )rG   rF   rL   )canceledZexpiredzBatch request was r   r   z=Error transforming Anthropic batch results to OpenAI format: N)r   decodestripsplitjsonloadsr1   -_transform_anthropic_message_to_openai_formatappenddumpsANTHROPIC_ERROR_STATUS_CODE_MAPjoinencode	Exceptionr   rN   )r   rA   rI   Ztransformed_linesZcontent_strlineZanthropic_resultrD   rE   Zresult_typerH   Zopenai_response_bodyZopenai_resultrN   Z	error_objerror_messageZ
error_typer-   Zerror_body_erroredZopenai_result_erroredZerror_body_canceledZopenai_result_canceledr:   er   r   r   r7      s   




zIAnthropicFilesHandler._transform_anthropic_batch_results_to_openai_formatrH   rI   c           
      C   sH  zft jdt|dd}t }tjddtjdddd	g|_	t
|d
ddddgdtjt dtt  dtt di id	}i |_|j|||ddd}|jdd}|dsd|dd|d< |W S  ty } z1td|  |dddtt |d
dddddddgddddd}	|	W  Y d}~S d}~ww )zX
        Transform a single Anthropic message to OpenAI chat completion format.
        rJ   rB   )r-   r.   stopr   r'   Z	assistant)r.   role)finish_reasonindexrG   modelzclaude-3-5-sonnet-20241022userZbatch_request)r`   r.   FZbatch_Zbatch_processingoptional_params)	rc   messagesstreamZ	call_type
start_timeZlitellm_call_idZfunction_idZlitellm_trace_idkwargsN)Zcompletion_responseZraw_responsemodel_responseZ	json_modeZprefix_promptT)Zexclude_nonerK   z7Error transforming Anthropic message to OpenAI format: zchat.completionrN   )rb   rG   ra   )Zprompt_tokensZcompletion_tokensZtotal_tokens)rK   objectcreatedrc   choicesusage)r8   r9   rS   rW   rZ   r   litellmZChoicesMessagerm   r	   r1   r   Zaretrieve_batchtimestrr   uuid4re   Ztransform_parsed_responseZ
model_dumpr[   r   rN   int)
r   rH   rI   Zmock_responserj   Zlogging_objr;   Zopenai_bodyr^   Zerror_responser   r   r   rU      sp   	


	



zCAnthropicFilesHandler._transform_anthropic_message_to_openai_format)NNr   N)__name__
__module____qualname____doc__r   r
   r   rr   r   floatr8   Timeoutrt   r   r<   boolr   r   r@   bytesr7   dictr   r   rU   r   r   r   r   r   (   sj    
Q
.
rr   )"r>   rS   rq   typingr   r   r   r   r8   ro   Zlitellm._loggingr   Zlitellm._uuidr   Z&litellm.llms.custom_httpx.http_handlerr   Z*litellm.litellm_core_utils.litellm_loggingr	   Zlitellm.types.llms.openair
   r   r   r   r   Zlitellm.types.utilsr   r   r   Zchat.transformationr   Zcommon_utilsr   rX   r   r   r   r   r   <module>   s0    