
    j"                         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mZ d dlmZ d dlmZmZmZmZ d dlmZ dd	lmZ  e       Z G d
 de      Zy)    N)Any	CoroutineOptionalTupleUnion)LlmProviders)GCSBucketBaseGCSLoggingConfig)get_async_httpx_client)CreateFileRequestFileContentRequestHttpxBinaryResponseContentOpenAIFileObject)VERTEX_CREDENTIALS_TYPES   ) VertexAIJsonlFilesTransformationc                       e Zd ZdZ fdZdedee   dee   dee   dee   de	e
ej                  f   d	ee   d
efdZdededee   de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Zded
eeef   fdZdedee   dee   dee   de	e
ej                  f   d	ee   d
efdZdededee   de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Z xZS )VertexAIFilesHandlerz~
    Handles Calling VertexAI in OpenAI Files API format v1/files/*

    This implementation uploads files on GCS Buckets
    c                 `    t         |           t        t        j                        | _        y )N)llm_provider)super__init__r   r   	VERTEX_AIasync_httpx_client)self	__class__s    }/Users/manta/Documents/Projects/TheRoad-I1/backend/.venv/lib/python3.12/site-packages/litellm/llms/vertex_ai/files/handler.pyr   zVertexAIFilesHandler.__init__!   s$    "8%//#
    create_file_dataapi_basevertex_credentialsvertex_projectvertex_locationtimeoutmax_retriesreturnc                 N  K   | j                  i        d {   }| j                  |d   |d          d {   }	|d   }
t        j                  |j	                  d            \  }}| j                  |	|
||       d {   }t        j                  ||	      S 7 7 g7 w)
N)kwargsvertex_instancepath_service_account)r)   service_account_jsonbucket_namefile)openai_file_content)headersr,   object_namelogging_payload)r   gcs_upload_response)get_gcs_logging_configconstruct_request_headersvertex_ai_files_transformation7transform_openai_file_content_to_vertex_ai_file_contentget_log_json_data_on_gcs3transform_gcs_bucket_response_to_openai_file_object)r   r   r    r!   r"   r#   r$   r%   gcs_logging_configr/   r,   r1   r0   r2   s                 r   async_create_filez&VertexAIFilesHandler.async_create_file'   s      6:5P5P 6Q 6
 0
 66./@A!34J!K 7 
 
 )7 +bb 0 4 4V < c 
	
 %)$>$>##+	 %? %
 
 .aa- 3 b 
 	
+0


s2   B%B B%B!A	B%B#B%!B%#B%	_is_asyncc	                     |r| j                  |||||||      S t        j                  | j                  |||||||            S )zn
        Creates a file on VertexAI GCS Bucket

        Only supported for Async litellm.acreate_file
        )r   r    r!   r"   r#   r$   r%   )r;   asynciorun)	r   r<   r   r    r!   r"   r#   r$   r%   s	            r   create_filez VertexAIFilesHandler.create_fileK   so    " ))!1!#5- /' *   ;;&&%5%'9#1$3# + ' 
 
r   file_idc                     t         j                  j                  |      }|j                  d      r|dd }n|}d|v r|j	                  dd      \  }}n|}d}t         j                  j                  |d      }||fS )az  
        Extract bucket name and object path from URL-encoded file_id.

        Expected format: gs%3A%2F%2Fbucket-name%2Fpath%2Fto%2Ffile
        Which decodes to: gs://bucket-name/path/to/file

        Returns:
            tuple: (bucket_name, url_encoded_object_path)
            - bucket_name: "bucket-name"
            - url_encoded_object_path: "path%2Fto%2Ffile"
        zgs://   N/r    )safe)urllibparseunquote
startswithsplitquote)r   rA   decoded_path	full_pathr,   object_pathencoded_object_paths          r   '_extract_bucket_and_object_from_file_idz<VertexAIFilesHandler._extract_bucket_and_object_from_file_ids   s     ||++G4""7+$QR(I$I)'0sA'>$K#KK$ll0020F///r   file_content_requestc           	        K   |j                  d      }|st        d      | j                  |      \  }}	dd|ii}
 | j                  dd|	i|
 d{   }|-t        j
                  j                  |      }t        d|       t        j
                  j                  |      }t        j                  d|d	d
it        j                  d|            }t        |      S 7 w)a  
        Download file content from GCS bucket for VertexAI files.

        Args:
            file_content_request: Contains file_id (URL-encoded GCS path)
            vertex_credentials: VertexAI credentials
            vertex_project: VertexAI project ID
            vertex_location: VertexAI location
            timeout: Request timeout
            max_retries: Max retry attempts

        Returns:
            HttpxBinaryResponseContent: Binary content wrapped in compatible response format
        rA   z+file_id is required in file_content_request standard_callback_dynamic_paramsgcs_bucket_namer0   Nz"Failed to download file from GCS:    zcontent-typezapplication/octet-streamGET)methodurl)status_codecontentr/   request)response )r7   
ValueErrorrQ   download_gcs_objectrG   rH   rI   httpxResponseRequestr   )r   rR   r!   r"   r#   r$   r%   rA   r,   rP   download_kwargsfile_contentrM   mock_responses                 r   afile_contentz"VertexAIFilesHandler.afile_content   s     . '**95JKK+/+W+W,
((
 /1BK0P
 6T55 
+
/>
 
 !<<//8LA,PQQ||++G4 #%?@MMLA	
 *=AA!
s   AC#C!BC#c	           
          |r| j                  ||||||      S t        j                  | j                  ||||||            S )a  
        Download file content from GCS bucket for VertexAI files.
        Supports both sync and async operations.

        Args:
            _is_async: Whether to run asynchronously
            file_content_request: Contains file_id (URL-encoded GCS path)
            api_base: API base (unused for GCS operations)
            vertex_credentials: VertexAI credentials
            vertex_project: VertexAI project ID
            vertex_location: VertexAI location
            timeout: Request timeout
            max_retries: Max retry attempts

        Returns:
            HttpxBinaryResponseContent or Coroutine: Binary content wrapped in compatible response format
        )rR   r!   r"   r#   r$   r%   )rg   r>   r?   )	r   r<   rR   r    r!   r"   r#   r$   r%   s	            r   re   z!VertexAIFilesHandler.file_content   si    < %%%9#5- /' &   ;;"")='9#1$3# + # 	 	r   )__name__
__module____qualname____doc__r   r   r   strr   r   floatra   Timeoutintr   r;   boolr   r   r@   r   rQ   r   r   rg   re   __classcell__)r   s   @r   r   r      sH   
"
+"
 3-"
 %%=>	"

 !"
 "#"
 uemm+,"
 c]"
 
"
H&& ,& 3-	&
 %%=>& !& "#& uemm+,& c]& 
35E+E!FF	G&P0s 0uSRUX 0:3B03B %%=>3B !	3B
 "#3B uemm+,3B c]3B 
$3Bj11 11 3-	1
 %%=>1 !1 "#1 uemm+,1 c]1 
"Ic38R.R$SS
1r   r   )r>   urllib.parserG   typingr   r   r   r   r   ra   litellmr   /litellm.integrations.gcs_bucket.gcs_bucket_baser	   r
   &litellm.llms.custom_httpx.http_handlerr   litellm.types.llms.openair   r   r   r   litellm.types.llms.vertex_air   transformationr   r5   r   r^   r   r   <module>r{      sL      9 9    J  B <!A!C \= \r   