
    ci:              
       >   d dl Z d dlmZmZmZmZ d dlmZ d dlmZ d dlm	Z
 d dlmZ d dlmZ d dlmZ d d	lmZ  ej&                  e      Zeej,                  ej.                  f   Zeej,                  ej2                  f   Zeej,                  ej6                  f   Zd
dddddidi dddddddddidi dddddddddidi ddddZ G d d ej<                        Z G d! d"      Z d#ejB                  d$eej,                  e"f   fd%Z#d$ej,                  fd&Z$y)'    N)ListOptionalSequenceUnion)base)initializer)utils)types)_generative_models)_utils)
struct_pb2zCode InterpreterzDThis extension generates and executes code in the specified languagecode_interpreter_toolz!Google Code Interpreter Extensionopen_api_gcs_uriz2gs://vertex-extension-public/code_interpreter.yamlGOOGLE_SERVICE_ACCOUNT_AUTH)	auth_typegoogle_service_account_config)namedescriptionapi_specauth_config)display_namer   manifestzVertex AI Searchz4This extension generates and executes search queriesvertex_ai_searchzVertex AI Search Extensionz2gs://vertex-extension-public/vertex_ai_search.yamlzWebpage Browserz/This extension fetches the content of a webpagewebpage_browserz Vertex Webpage Browser Extensionz1gs://vertex-extension-public/webpage_browser.yaml)code_interpreterr   r   c                       e Zd ZdZej
                  ZdZdZdZ	dZ
dZdZdef fd	Zed
d
d
d
ddeej$                  ej(                  f   dee   dee   dee   dee   f
d       Zedefd       Zdej$                  fdZdeej$                     fdZ	 	 ddedee   dee   deej$                  ef   fdZde jB                  ddfdZ"ed
ddedee   fd       Z# xZ$S ) 	Extensionz*Represents a Vertex AI Extension resource.	extensionget_extensionlist_extensionsdelete_extensionparse_extension_pathextension_pathextension_namec                     t         |   |       t        j                  j	                  t
        j                        | _        | j                  |      | _	        d| _
        d| _        y)a4  Retrieves an extension resource.

        Args:
            extension_name (str):
                Required. A fully-qualified resource name or ID such as
                "projects/123/locations/us-central1/extensions/456" or
                "456" when project and location are initialized or passed.
        resource_nameclient_classN)super__init__r   global_configcreate_client	aip_utils$ExtensionExecutionClientWithOverrideexecution_api_client_get_gca_resource_gca_resource	_api_spec_operation_schemas)selfr$   	__class__s     F/tmp/pip-target-z3e9_cxr/lib/python/vertexai/extensions/_extensions.pyr+   zExtension.__init__f   sd     	~6$/$=$=$K$K"GG %L %
! "33.3Q"&    N)r$   r   r   runtime_configr   r   r   r9   c          
      2   | j                  |       }t        j                  j                  ||       t	        j
                  ||xs | j                         |t        j                  |t	        j                                     }|r-t        j                  |t	        j                               |_        |j                  j                  t        j                  j!                         |      }t"        j%                  | |       |j'                         }	t"        j)                  | |	| j*                  d       |j-                  |	j.                        |_        t        j                  j3                  t4        j6                        |_        d|_        d|_        |S )a:  Creates a new Extension.

        Args:
            manifest (Union[dict[str, Any], ExtensionManifest]):
                Required. The manifest for the Extension to be created.
            extension_name (str):
                Optional. A fully-qualified extension resource name or extension
                ID such as "projects/123/locations/us-central1/extensions/456" or
                "456" when project and location are initialized or passed. If
                specifying the extension ID, it should be 4-63 characters, valid
                characters are lowercase letters, numbers and hyphens ("-"),
                and it should start with a number or a lower-case letter. If not
                provided, Vertex AI will generate a value for this ID.
            display_name (str):
                Optional. The user-defined name of the Extension.
                The name can be up to 128 characters long and can comprise any
                UTF-8 character.
            description (str):
                Optional. The description of the Extension.
            runtime_config (Union[dict[str, Any], RuntimeConfig]):
                Optional. Runtime config controlling the runtime behavior of
                this Extension. Defaults to None.

        Returns:
            Extension: The extension that was created.
        r&   )r   r   r   r   )parentr   zvertexai.preview.extensions)module_namer(   N)__new__r   %VertexAiResourceNounWithFutureManagerr+   r
   r   _generate_display_namer   to_protoExtensionManifestRuntimeConfigr9   
api_clientimport_extensionr   r,   common_location_path_LOGGERlog_create_with_lroresultlog_create_complete_resource_nounr1   r   r2   r-   r.   r/   r0   r3   r4   )
clsr   r$   r   r   r9   sdk_resourcer   operation_futurecreated_extensions
             r7   createzExtension.createw   sv   H {{3'22;;( 	< 	
 OO%E)C)C)E#__Xu/F/F/HI	
	 '-##%(I$ (22CC,,AAC D 
 	##C)9:,335##5	 	$ 	
 &2%C%C+00 &D &
" -8,E,E,S,S"GG -T -
) "&*.'r8   returnc                 .    | j                   j                  S )z/Full qualified resource name for the extension.)r2   r   r5   s    r7   r'   zExtension.resource_name   s     !!&&&r8   c                     | j                   .t        | j                  j                  j                        | _         | j                   S )z,Returns the (Open)API Spec of the extension.)r3   _load_api_specr2   r   r   rR   s    r7   r   zExtension.api_spec   s4    >>!+D,>,>,G,G,P,PQDN~~r8   c                     | j                   F| j                  j                  D cg c]!  }t        j                  |j
                        # c}| _         | j                   S c c}w )zBReturns the (Open)API schemas for each operation of the extension.)r4   r2   extension_operationsr   to_dictfunction_declaration)r5   ops     r7   operation_schemaszExtension.operation_schemas   sY    ""* ,,AA' r667'D# &&&	's   &Aoperation_idoperation_paramsruntime_auth_configc                     t        j                  | j                  ||      }|r-t        j                  |t        j
                               |_        | j                  j                  |      }t        |      S )a2  Executes an operation of the extension with the specified params.

        Args:
          operation_id (str):
              Required. The ID of the operation to be executed.
          operation_params (Union[dict[str, Any], Struct]):
              Optional. Parameters used for executing the operation. It should
              be in a form of map with param name as the key and actual param
              value as the value. E.g. if this operation requires a param
              "name" to be set to "abc", you can set this to {"name": "abc"}.
              Defaults to an empty dictionary.
          runtime_auth_config (Union[dict[str, Any], AuthConfig]):
              Optional. The Auth configuration to execute the operation.

        Returns:
            The result of executing the extension operation.
        )r   r[   r\   )
r
   ExecuteExtensionRequestr'   r   r@   
AuthConfigr]   r0   execute_extension_try_parse_execution_response)r5   r[   r\   r]   requestresponses         r7   executezExtension.execute   sk    . //##%-

 *0//#  "+G' ,,>>wG,X66r8   contentsQueryExtensionResponsec                    t        j                  | j                  t        j                  |            }| j
                  j                  |      }|j                  rt        |j                        t        j                  |      S )a.  Queries an extension with the specified contents.

        Args:
          contents (ContentsType):
              Required. The content of the current
              conversation with the model.
              For single-turn queries, this is a single
              instance. For multi-turn queries, this is a
              repeated field that contains conversation
              history + latest request.

        Returns:
            The result of querying the extension.

        Raises:
            RuntimeError: If the response contains an error.
        )r   rf   )r
   QueryExtensionRequestr'   r    _content_types_to_gapic_contentsr0   query_extensionfailure_messageRuntimeErrorrg   _from_gapic)r5   rf   rc   rd   s       r7   queryzExtension.query   sn    * --##'HHR
 ,,<<WE##x7788%11(;;r8   )r9   r   c                b   |r(t        j                  |t        j                               }|dk(  r|rXt	        |dd      sKt        d      |dk(  r'|st        d      |r,t	        |dd      st        d      |d	k(  rnt        d
|       t        |   }| j                  |d   |d   |d   |      S )ap  Creates a new Extension from the set of first party extensions.

        Args:
            name (str):
                Required. The name of the extension in the hub to be created.
                Supported values are "code_interpreter", "vertex_ai_search" and
                "webpage_browser".
            runtime_config (Union[dict[str, Any], RuntimeConfig]):
                Optional. Runtime config controlling the runtime behavior of
                the Extension. Defaults to None.

        Returns:
            Extension: The extension that was created.

        Raises:
            ValueError: If the `name` is not supported in the hub.
            ValueError: If the `runtime_config` is specified but inconsistent
            with the name (e.g. the name was "code_interpreter" but the
            runtime_config was based on "vertex_ai_search_runtime_config").
        r   code_interpreter_runtime_configNzJcode_interpreter_runtime_config is required for code_interpreter extensionr   z9runtime_config is required for vertex_ai_search extensionvertex_ai_search_runtime_configzJvertex_ai_search_runtime_config is required for vertex_ai_search extensionr   zUnsupported 1P extension name: r   r   r   )r   r   r   r9   )r   r@   r
   rB   getattr
ValueError_VERTEX_EXTENSION_HUBrO   )rK   r   r9   extension_infos       r7   from_hubzExtension.from_hub  s    6 #__##%N %%g1'
 !1  ''! O  g1'
 !1  &&>tfEFF.t4zz'7&}5#J/)	  
 	
r8   )NN)%__name__
__module____qualname____doc__r.   #ExtensionRegistryClientWithOverrider)   rJ   _getter_method_list_method_delete_method_parse_resource_name_method_format_resource_name_methodstrr+   classmethodr   r   JsonDictr
   rA   r   _RuntimeConfigOrJsonrO   propertyr'   r   r   rZ   _StructOrJson_AuthConfigOrJsonre   r   ContentsTypero   rw   __classcell__)r6   s   @r7   r   r   [   s   4@@L N$N$L'N"8#3 's '" 
 )-&*%)9=I)@)@@AI !	I
 smI c]I !!56I IV 's ' '&// '8FOO#< ' 59;?	"7"7 #=1"7 &&78	"7
 
v#	$"7H<$11< 
"<< 
 :>	A
A
 !!56	A
 A
r8   r   c                   d    e Zd ZdZdeej                     fdZede	j                  dd fd       Zy)rg   z=A class representing the response from querying an extension.stepsc                     || _         y)z<Initializes the QueryExtensionResponse with the given steps.Nr   )r5   r   s     r7   r+   zQueryExtensionResponse.__init__a  s	    
r8   rd   rP   c                     | |j                   D cg c]X  }t        j                  |j                  D cg c]!  }t        j                  j                  |      # c}|j                        Z c}}      S c c}w c c}}w )z7Creates a QueryExtensionResponse from a gapic response.)partsroler   )r   r   Contentr   Partrn   r   )rK   rd   cps       r7   rn   z"QueryExtensionResponse._from_gapice  sp    
  "
 	 #**KL77Sa-22>>qAS
 	
 Ts   "A=
&A8A=
8A=
N)rx   ry   rz   r{   r   r   r   r+   r   r
   rg   rn    r8   r7   rg   rg   ^  sG    Gd#5#=#=>  
33
	!
 
r8   rg   rd   rP   c                 ~    | j                   }	 t        j                  |      }|S # t        j                  $ r Y |S w xY w)N)contentjsonloadsJSONDecodeError)rd   r   s     r7   rb   rb   u  sH     ##G**W% N  Ns   % <<c                     | j                   r9t        j                  j                         }|j	                  | j                         S | j
                  r)t        j                  j                  | j
                        S i S )zBLoads the (Open)API Spec of the extension and converts it to JSON.)open_api_yamlr.   
yaml_utils_maybe_import_yaml	safe_loadr   	load_yaml)r   yamls     r7   rT   rT     s_    ##668~~h4455		"	"##--h.G.GHHIr8   )%r   typingr   r   r   r   google.cloud.aiplatformr   r   r	   r.   google.cloud.aiplatform_v1beta1r
   vertexai.generative_modelsr   vertexai.reasoning_enginesr   google.protobufr   Loggerrx   rF   r   r`   r   Structr   rB   r   ru   r>   r   rg   ExecuteExtensionResponser   rb   rT   r   r8   r7   <module>r      sv     2 2 ( / 6 1 9 - &
$++h
&//5+;+;;< fooz'8'889V__e.A.AAB 
 +R ,>"H ;13
( +M&7"H ;13
$ *H%="G ;13
K6 r@
:: @
F
 
.,,
6??C  r8   