
    g"              
          U d dl Z d dlm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 d dlmZ d dlmZ d d	lmZ d dl  e       Z e       aeed
<   defdZd#dee   fdZdefdZde de dee    dee    dejB                  f
dZ"ejG                  dg dddgd      ejG                  dg dddg      de ded efd!              Z$dede fd"Z%y)$    N)Optional)	APIRouterHTTPExceptionRequestResponsestatus)verbose_proxy_logger) vertex_fine_tuning_apis_instance)*)user_api_key_auth)create_pass_through_route)get_secret_strdefault_vertex_configreturnc                  T    t        t        d      t        d      t        d            S )a  
    Helper to get vertex pass through config from environment variables

    The following environment variables are used:
    - DEFAULT_VERTEXAI_PROJECT (project id)
    - DEFAULT_VERTEXAI_LOCATION (location)
    - DEFAULT_GOOGLE_APPLICATION_CREDENTIALS (path to credentials file)
    DEFAULT_VERTEXAI_PROJECTDEFAULT_VERTEXAI_LOCATION&DEFAULT_GOOGLE_APPLICATION_CREDENTIALS)vertex_projectvertex_locationvertex_credentials)VertexPassThroughCredentialsr        g/var/www/openai/venv/lib/python3.12/site-packages/litellm/proxy/vertex_ai_endpoints/vertex_endpoints.py_get_vertex_env_varsr      s,     (%&@A&'BC)*RS r   configc                     | t               ayt        | t              rS| j	                         D ]@  \  }}t        |t
              s|j                  d      s)t        j                  |      | |<   B t        di | ay)aL  Sets vertex configuration from provided config and/or environment variables

    Args:
        config (Optional[dict]): Configuration dictionary
        Example: {
            "vertex_project": "my-project-123",
            "vertex_location": "us-central1",
            "vertex_credentials": "os.environ/GOOGLE_CREDS"
        }
    Nzos.environ/r   )
r   r   
isinstancedictitemsstr
startswithlitellm
get_secretr   )r   keyvalues      r   set_default_vertex_configr(   '   sn     ~ 4 6&$ ,,.JC%%%*:*:=*I%007s ) 9B6Br   ec           
         t        j                  dj                  t        |                    t        j                  t        j                                t        | t              r\t        t        | dt        | j                              t        | dd      t        | dd      t        | dt        j                              S t        |        }t        t        | d|      t        | dd      t        | dd      t        | dd            S )	NzLlitellm.proxy.proxy_server.v1/projects/tuningJobs(): Exception occurred - {}messagetypeNoneparamstatus_code)r+   r,   r.   codei  )r	   errorformatr"   debug	traceback
format_excr   r   ProxyExceptiongetattrdetailr   HTTP_400_BAD_REQUEST)r)   	error_msgs     r   exception_handlerr;   A   s    V]]F	

 y3356!]#Ay#ahh-8FF+!Wf-M6+F+FG	
 	
 1vh	Ay)4FF+!Wf-M3/	
 	
r   base_urlrequested_routedefault_vertex_locationdefault_vertex_projectc                     t        j                  |       }d|v r|j                  |      }|S 	 d}d|v rd}dj                  |||      }d|z   |z   }|j                  |      }|S )a<  
    Allow user to specify their own project id / location.

    If missing, use defaults

    Handle cachedContent scenario - https://github.com/BerriAI/litellm/issues/5460

    Constructed Url:
    POST https://LOCATION-aiplatform.googleapis.com/{version}/projects/PROJECT_ID/locations/LOCATION/cachedContents
    	locations)pathv1cachedContentv1beta1z{}/projects/{}/locations/{}/)httpxURL	copy_withr2   )	r<   r=   r>   r?   new_base_urlupdated_urlvertex_versionbase_requested_routeupdated_requested_routes	            r   construct_target_urlrO   Y   s      99X&Lo%",,/,B
 04N/)"8??.0G "$88?J((.E(FKr   z/vertex-ai/{endpoint:path})GETPOSTPUTDELETEPATCHzVertex AI Pass-throughzpass-throughF)methodstagsinclude_in_schemaz/vertex_ai/{endpoint:path})rU   rV   endpointrequestfastapi_responsec                 ,  K   t        j                  |       j                  }ddl}t	        j
                  d|        i }t        |      }t        ||       d{   }d}d}	t        j                  t        |j                        xs i }t	        j
                  d|       |j                  d|       }
|
r|
j                  d      nd}	d	|	 d
}|j                  dd       |j                  dd       nt        j                  }t        j                  }	t        j                   }d	|	 d
}t#        j$                  ||d       d{   \  }}t#        j&                  d|d|||	ddd	      \  }}dd| i}|}t	        j
                  d|       |j)                  d      sd|z   }t+        |||	|      }t	        j
                  d|       t-        |      }d}dt-        |      v rd}|dz  }t/        | ||      } |||||       d{   }|S 7 7 7 w)zp
    Call LiteLLM proxy via Vertex AI SDK.

    [Docs](https://docs.litellm.ai/docs/pass_through/vertex_ai)
    r   Nzrequested endpoint %s)rY   )rY   api_keyz;default_vertex_config  not set, incoming request headers %sz/locations/([^/]+)   zhttps://z-aiplatform.googleapis.com/zcontent-lengthhostvertex_ai_beta)credentials
project_idcustom_llm_provider F)	modelauth_headergemini_api_keyr   r   r   streamrb   api_baseAuthorizationBearer zrequest_route %srF   )r<   r=   r>   r?   zupdated url %srg   Tz?alt=sse)rX   targetcustom_headers)rg   )rG   rH   rB   rer	   r3   get_litellm_virtual_keyr   r   r   r    headerssearchgrouppopr   r   r
   _ensure_access_token_async_get_token_and_urlr#   rO   r"   r   )rX   rY   rZ   encoded_endpointrm   ro   api_key_to_useuser_api_key_dictr   r   matchbase_target_urlr   _auth_headerre   _request_routerK   rk   is_streaming_requestendpoint_funcreceived_values                         r   vertex_proxy_router      s_    * yy*//6AG,W=N/ 
 NO++3w'-2""I7	

 		/:,1%++a.t$_$55PQ$d+FD!.==/??2EE$_$55PQ 3MM.)$4  	%n :LL$1)+ 0

Q w{m4
 %M1=A &&s+!11 ' ( /-	K /= F 3{###* .M
 )#	 N u8ns8   AHHC*HHC HHHHHc                 ~    | j                   j                  d      }|rd| S | j                   j                  dd      S )z
    Extract and format API key from request headers.
    Prioritizes x-litellm-api-key over Authorization header.


    Vertex JS SDK uses `Authorization` header, we use `x-litellm-api-key` to pass litellm virtual key

    zx-litellm-api-keyrj   ri   rc   )ro   get)rY   litellm_api_keys     r   rn   rn      sA     oo))*=>O)**??33r   )N)&r4   typingr   rG   fastapir   r   r   r   r   r$   litellm._loggingr	   litellm.fine_tuning.mainr
   litellm.proxy._types$litellm.proxy.auth.user_api_key_authr   ;litellm.proxy.pass_through_endpoints.pass_through_endpointsr   litellm.secret_managers.mainr   -litellm.types.passthrough_endpoints.vertex_airouterr   r   __annotations__r   r    r(   	Exceptionr;   r"   rH   rO   	api_router   rn   r   r   r   <module>r      sA      G G  1 E " B 8 ;	6R6T 3 T:  Chtn C4
 
0$$$ &c]$ %SM	$
 YY$N  5
"N	3	    5
"N	3  
kkk kk\4W 4 4r   