
    i                         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
e      Zy)    N)Any	CoroutineOptionalTupleUnion)LlmProviders)get_async_httpx_client)FileContentRequestHttpxBinaryResponseContent)SpecialEnums   )
BaseAWSLLMc                        e Zd ZdZ fdZdedefdZdedeeef   fdZde	d	e
d
eeej                  f   dee   def
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Z x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                 `    t         |           t        t        j                        | _        y )N)llm_provider)super__init__r	   r   BEDROCKasync_httpx_client)self	__class__s    s/Users/manta/Documents/Projects/TheRoad-I1/.venv/lib/python3.12/site-packages/litellm/llms/bedrock/files/handler.pyr   zBedrockFilesHandler.__init__   s$    "8%--#
    file_idreturnc                 l   	 |dt        |       dz  z  z   }t        j                  |      j                         }|j	                  t
        j                  j                        r,d|v r(|j                  d      d   j                  d      d   }|S |j	                  d      r|S d| S # t        $ r Y #w xY w)ay  
        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   LITELM_MANAGED_FILE_ID_PREFIXvaluesplit	Exception)r   r   paddeddecodeds3_uris        r   _extract_s3_uri_from_file_idz0BedrockFilesHandler._extract_s3_uri_from_file_id    s    	ss7|ma&788F..v6==?G !!,"L"L"R"RS(G3$]]+@A!DJJ3OPQRF!M
 g&N wi    		s   BB' '	B32B3r.   c                     |j                  d      st        d| d      |dd }d|v r|j                  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_keys        r   _parse_s3_uriz!BedrockFilesHandler._parse_s3_uriD   sy       ))&1ab 
 abz$;&*jja&8#K
 J&& KJJ&&r   file_content_requestoptional_paramstimeoutmax_retriesc                   K   ddl }ddlm} |j                  d      }|st	        d      | j                  |      }| j                  |      \  }	}
| j                  |d      }| j                  |j                  d      |j                  d	      |j                  d
      ||j                  d      |j                  d      |j                  d      |j                  d      |j                  d      	      }|j                  d|j                  |j                  |j                  || j                               }	 |j                  |	|
      }|d   j                         }t%        j&                  d|ddit%        j(                  d|            }t+        |      S # t         $ r}t	        d| dt#        |             d}~ww xY ww)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_requestr3   )r:   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)	r@   rA   rB   aws_region_namerC   rD   rE   rF   rG   s3)r@   rA   rB   region_nameverify)BucketKeyBodyz!Failed to download file from S3: z	. Error:    zcontent-typezapplication/octet-streamGET)methodurl)status_codecontentheadersrequest)response)boto3botocore.credentialsr>   getr4   r/   r8   _get_aws_region_nameget_credentialsclient
access_key
secret_keytoken_get_ssl_verify
get_objectreadr+   strhttpxResponseRequestr   )r   r9   r:   r;   r<   rX   r>   r   r.   r6   r7   rH   credentials	s3_clientrW   file_contentemock_responses                     r   afile_contentz!BedrockFilesHandler.afile_content^   s    & 	4&**95JKK 227;"&"4"4V"<Z 33+2 4 
 $(#7#7-112EF"1"5"56M"N-112EF+,001CD,001CD)--o>#2#6#67O#P,001CD $8 
$
 LL)44"-"8"8)//''') ! 
		 ++;J+OH#F+002L  #%?@MMF;	
 *=AA  	3F89SVHM 	s*   D6G9&F <G	G$F>>GG	_is_asyncapi_basec                     |r| j                  ||||      S t        j                  | j                  ||||            S )aX  
        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
        )r9   r:   r;   r<   )rm   asynciorun)r   rn   r9   ro   r:   r;   r<   s          r   rj   z BedrockFilesHandler.file_content   s]    4 %%%9 /'	 &   ;;"")=$3# +	 #  r   )__name__
__module____qualname____doc__r   rd   r/   r   r8   r
   dictr   floatre   Timeoutr   intr   rm   boolr   r   rj   __classcell__)r   s   @r   r   r      s	   
"!C "!C "!H'C 'E#s(O '4IB0IB IB uemm+,	IB
 c]IB 
$IBV)) 1) 3-	)
 ) uemm+,) c]) 
"Ic38R.R$SS
)r   r   )rq   r$   typingr   r   r   r   r   re   litellmr   &litellm.llms.custom_httpx.http_handlerr	   litellm.types.llms.openair
   r   litellm.types.utilsr   base_aws_llmr   r    r   r   <module>r      s5      9 9    I - %@* @r   