Ë
    uPêj"#  ã                   óê   — d dl Z d dlZd dlZd dlZd dlmZmZ d dlmZm	Z	 d dl
mZ d dlZd dlmZ d dl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
lmZmZ d dlmZ d dlm Z  ddl!m"Z"  G d„ de«      Z#y)é    N)Ú	CoroutineÚMapping)ÚAnyÚFinal)Úunquote)ÚLlmProviders)ÚGCSBucketBaseÚGCSLoggingConfig)ÚVERTEX_AI_MANAGED_GCS_PREFIXÚ"should_allow_legacy_cloud_file_idsÚvalidate_managed_cloud_file_id)ÚLogging)Úget_async_httpx_client)ÚFileContentRequestÚHttpxBinaryResponseContent)ÚVERTEX_CREDENTIALS_TYPES)ÚStandardCallbackDynamicParamsé   )ÚVertexAIFilesConfigc                   óv  ‡ — e Zd ZdZˆ fd„Zdeeef   dz  dedz  de	edz  edz  f   fd„Z
	 dded	ededz  de	eef   fd
„Z	 ddededz  dedz  dedz  deej                   z  dedz  dedz  defd„Z	 ddedededz  dedz  dedz  dedz  deej                   z  dedz  dedz  deeeeef   z  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    €úi/home/oem/CyberBrain26-unified/.venv/lib/python3.12/site-packages/litellm/llms/vertex_ai/files/handler.pyr   zVertexAIFilesHandler.__init__(   s$   ø€ Ü‰ÑÔÜ"8Ü%×/Ñ/ô#
ˆÕó    Úlitellm_paramsNÚvertex_credentialsÚreturnc                 ó~  — |xs i }|j                  d«      xs |j                  d«      }t        |t        «      r|nt        j                  d«      }|j                  d«      xs |}t        |t
        «      rt        j                  |«      }||fS t        |t        «      r|}||fS t        j                  d«      }||fS )aP  
        Resolve the GCS bucket and service-account credentials for the read/content path.

        Sources them from the deployment's ``litellm_params`` (``gcs_bucket_name`` /
        ``bucket_name`` and ``vertex_credentials``), mirroring the write path in
        ``VertexAIFilesConfig._get_configured_bucket_name``, and falls back to the global
        ``GCS_BUCKET_NAME`` / ``GCS_PATH_SERVICE_ACCOUNT`` env vars. This lets Vertex batch
        run entirely at the model-group level, so output written to a per-model bucket is
        readable without setting the global env vars.
        Úgcs_bucket_nameÚbucket_nameÚGCS_BUCKET_NAMEr#   ÚGCS_PATH_SERVICE_ACCOUNT)ÚgetÚ
isinstanceÚstrÚosÚgetenvÚdictÚjsonÚdumps)r   r"   r#   ÚparamsÚbucket_candidateÚconfigured_bucket_nameÚcredentialsÚpath_service_accounts           r    Ú_resolve_read_gcs_configz-VertexAIFilesHandler._resolve_read_gcs_config.   sÇ   € ð /=Ò.BÀˆØ"(§*¡*Ð->Ó"?Ò"\À6Ç:Á:ÈmÓC\ÐÜ5?Ð@PÔRUÔ5VÑ!1Ô\^×\eÑ\eÐfwÓ\xÐà#ŸZ™ZÐ(<Ó=ÒSÐASˆÜ�k¤4Ô(Ü/3¯z©z¸+Ó/FÐ ð &Ð';Ð;Ð;ô ˜¤SÔ)Ø#.Ð ð &Ð';Ð;Ð;ô $&§9¡9Ð-GÓ#HÐ à%Ð';Ð;Ð;r!   Úfile_idr4   c           	      ó>   — t        |d|t        ft        |«      ¬«      S )aE  
        Validate and extract bucket name and object path from file_id.

        Expected format: gs://bucket-name/litellm-vertex-files/path/to/file

        Returns:
            tuple: (bucket_name, object_path)
            - bucket_name: "bucket-name"
            - object_path: "litellm-vertex-files/path/to/file"
        zgs://)r8   Úschemer4   Úallowed_object_prefixesÚallow_legacy_cloud_file_ids)r   r   r   )r   r8   r4   r"   s       r    Ú'_extract_bucket_and_object_from_file_idz<VertexAIFilesHandler._extract_bucket_and_object_from_file_idK   s(   € ô  .ØØØ#9Ü%AÐ$CÜ(JÈ>Ó(Zô
ð 	
r!   Úfile_content_requestÚvertex_projectÚvertex_locationÚtimeoutÚmax_retriesc           
   ƒ   óŒ  K  — |j                  d«      }|st        d«      ‚| j                  ||¬«      \  }	}
t        |	|
¬«      }| j	                  d|i¬«      ƒ d{  –—† }| j                  ||d   |¬	«      \  }}d||d
   dœi} | j                  dd|i|¤Žƒ d{  –—† }t        |«      }|€t        d|› �«      ‚t        j                  d|dt        t        |«      «      dœt        j                  d|¬«      ¬«      }t        «       }t        dg ddt        j                  «       dd¬«      }|j!                  ||i ¬«      S 7 Œä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
        r8   z+file_id is required in file_content_request)r"   r#   )r&   Úgcs_path_service_accountÚ standard_callback_dynamic_params)ÚkwargsNr'   )r8   r4   r"   r6   Úobject_namez"Failed to download file from GCS: éÈ   zapplication/octet-stream)zcontent-typezcontent-lengthÚGET)ÚmethodÚurl)Ústatus_codeÚcontentÚheadersÚrequestÚ FÚafile_content)ÚmodelÚmessagesÚstreamÚ	call_typeÚ
start_timeÚlitellm_call_idÚfunction_id)Úraw_responseÚlogging_objr"   © )r*   Ú
ValueErrorr7   r   Úget_gcs_logging_configr=   Údownload_gcs_objectr   ÚhttpxÚResponser,   ÚlenÚRequestr   r   ÚtimeÚtransform_file_content_response)r   r>   r#   r?   r@   rA   rB   r"   r8   r4   r6   Údynamic_paramsÚgcs_logging_configr'   Úobject_pathÚdownload_kwargsÚfile_contentÚdecoded_file_idÚmock_responseÚconfigrZ   s                        r    rQ   z"VertexAIFilesHandler.afile_contentc   s¨  è ø€ ð0 .×1Ñ1°)Ó<ˆÙÜÐJÓKÐKà7;×7TÑ7TØ)Ø1ð 8Uó 8
Ñ4ÐÐ 4ô !>Ø2Ø%9ô!
ˆð =A×<WÑ<WØ6¸ÐGð =Xó =
÷ 7
Ðð $(×#OÑ#OØØ#5°mÑ#DØ)ð $Pó $
Ñ ˆ�[ð /Ø#.Ø,>Ð?UÑ,Vñ1ð"
ˆð %= D×$<Ñ$<Ñ$hÈÐ$hÐXgÑ$h×hˆÜ!(¨Ó!1ˆàÐÜÐAÀ/ÐARÐSÓTÐTä$Ÿ~™~ØØ à :Ü"%¤c¨,Ó&7Ó"8ñô —M‘M¨°OÔDô 
ˆô ,Ó-ˆô %ØØØØ%Ü—y‘y“{ØØô
ˆð ×5Ñ5Ø&°KÐPRð 6ó 
ð 	
ð]7
øð  iús%   ‚AEÁE Á?EÂEÂB%EÅEÚ	_is_asyncÚapi_basec
                 óŒ   — |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
        )r>   r#   r?   r@   rA   rB   r"   )rQ   ÚasyncioÚrun)
r   rm   r>   rn   r#   r?   r@   rA   rB   r"   s
             r    ri   z!VertexAIFilesHandler.file_content¹   so   € ñ: Ø×%Ñ%Ø%9Ø#5Ø-Ø /ØØ'Ø-ð &ó ð ô —;‘;Ø×"Ñ"Ø)=Ø'9Ø#1Ø$3Ø#Ø +Ø#1ð #ó ó
ð 
r!   )N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r,   Úobjectr   Útupler7   r/   r=   r   Úfloatr_   ÚTimeoutÚintr   rQ   Úboolr   r   ri   Ú__classcell__)r   s   @r    r   r   !   s±  ø„ ñô
ð<à  V Ñ,¨tÑ3ð<ð 5°tÑ;ð<ð 
ˆs�T‰z˜3 ™:Ð%Ñ	&ó	<ðB '+ñ	
àð
ð !$ð
ð ˜t™ð	
ð
 
ˆs�Cˆx‰ó
ð@ '+ñT
à0ðT
ð 5°tÑ;ðT
ð ˜d™
ð	T
ð
 ˜t™ðT
ð ˜Ÿ™Ñ&ðT
ð ˜4‘ZðT
ð ˜t™ðT
ð 
$óT
ð@ '+ñ2àð2ð 1ð2ð ˜‘*ð	2ð
 5°tÑ;ð2ð ˜d™
ð2ð ˜t™ð2ð ˜Ÿ™Ñ&ð2ð ˜4‘Zð2ð ˜t™ð2ð 
$ i°°SÐ:TÐ0TÑ&UÑ	U÷2r!   r   )$rp   r0   r-   rc   Úcollections.abcr   r   Útypingr   r   Úurllib.parser   r_   Úlitellmr   Ú/litellm.integrations.gcs_bucket.gcs_bucket_baser	   r
   Ú1litellm.litellm_core_utils.cloud_storage_securityr   r   r   Ú*litellm.litellm_core_utils.litellm_loggingr   Ú&litellm.llms.custom_httpx.http_handlerr   Úlitellm.types.llms.openair   r   Úlitellm.types.llms.vertex_air   Úlitellm.types.utilsr   Útransformationr   r   r[   r!   r    ú<module>r‰      sV   ðÛ Û Û 	Û ß .ß Ý  ã å  ÷÷ñ õ
 ?Ý I÷õ BÝ =å /ôJ˜=õ Jr!   