o
    ưiy                     @   s   d dl Z 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 d dlmZ ddlmZ G d	d
 d
eZdS )    N)Any	CoroutineOptionalTupleUnion)LlmProviders)get_async_httpx_client)FileContentRequestHttpxBinaryResponseContent)SpecialEnums   )
BaseAWSLLMc                       s   e Zd ZdZ fddZdedefddZdedeeef fd	d
Zde	de
deeejf dee def
ddZdede	dee de
deeejf dee deeeeeef f fddZ  ZS )BedrockFilesHandlerz
    Handles downloading files from S3 for Bedrock batch processing.
    
    This implementation downloads files from S3 buckets where Bedrock
    stores batch output files.
    c                    s   t    ttjd| _d S )N)Zllm_provider)super__init__r   r   ZBEDROCKZasync_httpx_client)self	__class__ Y/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/bedrock/files/handler.pyr      s   
zBedrockFilesHandler.__init__file_idreturnc                 C   s   z.|dt | d   }t| }|tjjr-d|v r-|dd dd }|W S W n	 t	y7   Y nw |dr?|S d| S )a  
        Extract S3 URI from encoded file ID.
        
        The file ID can be in two formats:
        1. Base64-encoded unified file ID containing: llm_output_file_id,s3://bucket/path
        2. Direct S3 URI: s3://bucket/path
        
        Args:
            file_id: Encoded file ID or direct S3 URI
            
        Returns:
            S3 URI (e.g., "s3://bucket-name/path/to/file")
        =   zllm_output_file_id,   ;r   s3://)
lenbase64urlsafe_b64decodedecode
startswithr   ZLITELM_MANAGED_FILE_ID_PREFIXvaluesplit	Exception)r   r   paddeddecodeds3_urir   r   r   _extract_s3_uri_from_file_id    s   

z0BedrockFilesHandler._extract_s3_uri_from_file_idr'   c                 C   sV   | dstd| d|dd }d|v r#|dd\}}||fS |}d}||fS )	z
        Parse S3 URI to extract bucket name and object key.
        
        Args:
            s3_uri: S3 URI (e.g., "s3://bucket-name/path/to/file")
            
        Returns:
            Tuple of (bucket_name, object_key)
        r   zInvalid S3 URI format: z0. Expected format: s3://bucket-name/path/to/file   N/r    )r!   
ValueErrorr#   )r   r'   pathbucket_name
object_keyr   r   r   _parse_s3_uriD   s   

z!BedrockFilesHandler._parse_s3_urifile_content_requestoptional_paramstimeoutmax_retriesc                    s8  ddl }ddlm} |d}|std| |}| |\}	}
| j|dd}| j|d|d	|d
||d|d|d|d|dd	}|j	d|j
|j|j||  d}z|j|	|
d}|d  }W n ty } ztd| dt| d}~ww tjd|dditjd|dd}t|dS )a  
        Download file content from S3 bucket for Bedrock files.
        
        Args:
            file_content_request: Contains file_id (encoded or S3 URI)
            optional_params: Optional parameters containing AWS credentials
            timeout: Request timeout
            max_retries: Max retry attempts
            
        Returns:
            HttpxBinaryResponseContent: Binary content wrapped in compatible response format
        r   N)Credentialsr   z+file_id is required in file_content_requestr+   )r2   modelaws_access_key_idaws_secret_access_keyaws_session_tokenaws_session_nameaws_profile_nameaws_role_nameaws_web_identity_tokenaws_sts_endpoint)	r7   r8   r9   aws_region_namer:   r;   r<   r=   r>   Zs3)r7   r8   r9   Zregion_nameverify)ZBucketKeyZBodyz!Failed to download file from S3: z	. Error:    zcontent-typezapplication/octet-streamGET)methodurl)status_codecontentheadersrequest)response)boto3Zbotocore.credentialsr5   getr,   r(   r0   Z_get_aws_region_nameZget_credentialsclientZ
access_keyZ
secret_keytokenZ_get_ssl_verifyZ
get_objectreadr$   strhttpxResponseRequestr
   )r   r1   r2   r3   r4   rK   r5   r   r'   r.   r/   r?   credentialsZ	s3_clientrJ   file_contenteZmock_responser   r   r   afile_content\   sX   



z!BedrockFilesHandler.afile_content	_is_asyncapi_basec                 C   s.   |r| j ||||dS t| j ||||dS )al  
        Download file content from S3 bucket for Bedrock files.
        Supports both sync and async operations.
        
        Args:
            _is_async: Whether to run asynchronously
            file_content_request: Contains file_id (encoded or S3 URI)
            api_base: API base (unused for S3 operations)
            optional_params: Optional parameters containing AWS credentials
            timeout: Request timeout
            max_retries: Max retry attempts
            
        Returns:
            HttpxBinaryResponseContent or Coroutine: Binary content wrapped in compatible response format
        )r1   r2   r3   r4   )rW   asynciorun)r   rX   r1   rY   r2   r3   r4   r   r   r   rU      s   z BedrockFilesHandler.file_content)__name__
__module____qualname____doc__r   rP   r(   r   r0   r	   dictr   floatrQ   Timeoutr   intr
   rW   boolr   r   rU   __classcell__r   r   r   r   r      sB    $
Ir   )rZ   r   typingr   r   r   r   r   rQ   Zlitellmr   Z&litellm.llms.custom_httpx.http_handlerr   Zlitellm.types.llms.openair	   r
   Zlitellm.types.utilsr   Zbase_aws_llmr   r   r   r   r   r   <module>   s    