
    ci                       U d Z ddlZddlZddlZddlmZ ddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddl Z ddl!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jV                  d
k\  rddlm,Z, nddl-m,Z, 	 ej\                  Z/ee0   e1d<   	  ejf                         Z4ee0ee0   f   e1d<   	 ejj                  Z6e7e0   e1d<   ejp                  rddl9m:Z: e:jv                  Z<e,e1d<   n	 ddl9m:Z: e:jv                  Z<e=e   e1d<   ejp                  rddl?Z?e?j                  j                  ZBn#	 ddl?Z?e?j                  j                  ZBe=e   e1d<   	 ddlCmDZDmEZEmFZFmGZGmHZH ddlImJZJmKZK eDZDeEZEeFZFeJZJeKZKeGZGeHZHdZLdZMdZNdZOdZPdZQ eRe/      j                  e6      ZTdZUdZV e7g d      ZWdZXdZYdZZd Z[d!Z\d"Z]d#Z^d$Z_d%Z` e7d&d'g      Zad(Zbd)Zcd*Zdd+Zed,Zfd-Zgd.Zhd/Zid0Zjd1Zkd2Zld3Zmd4Znd5Zod6Zpeje^eOeXekebePeZiZqeje_eOeYeke`ePe[iZr e
j                  d7      Ztej                   G d8 d9e             Zvej                   G d: d;e             Zwej                   G d< d=e             Zxej                   G d> d?e             Zyej                   G d@ dAe             Zzej                   G dB dCe             Z{ej                   G dD dEe             Z|ejp                  rddFl}m~Z~ e~Ze,e1dG<   n	 ddFl}m~Z~ e~Zee,   e1dG<   eeewexe|eveyezf   Z G dH dIedJK      Z G dL dMe{e|      Z G dN dOe      Z G dP dQe      Z G dR dSe      Zee*j                  e*j                  e*j                  f   Z G dT dUe      Z G dV dWe      ZddXe0dYe0dZe0fd[Zd\d]dXe0d^ed_edZefd`Zd\d]dXe0d^ed_edZefdaZddbdcee0e0f   ddeee0   ee0ed   f   f   deeee0      dZefdfZdgedhee0ee0   f   dZee!j                     fdiZdjeee0ef      dZee!j                     fdkZdlej(                  dZefdmZdi g dndoedpef   dqee0   dree0e0f   dsee0   dZee0ef   f
dtZdee0   dgedZee0ef   fduZddvdwe0dxe0dye0dzee   dZe<f
d{ZdgedZee0ee0   f   fd|ZdZej8                  fd}ZdZej8                  fd~ZdZej8                  fdZdZej8                  fdZdZej8                  fdZddee0   dZee0ed   f   fdZddvdgee   dceee0      deee0      dwe0dxe0dye0de0dzee   dZdfdZddd!e*jH                  deee0ee0e0gedpef   f   f      dZdfdZdddddedeee0      deee0ee0   f      deee0ef      dZee0e0f   f
dZde!j                  dZee0ef   fdZ	 ddeee0ef   e!j                  f   dee!j                     dZe!j                  fdZdgede<de0dZdfdZdcee0   de<de0dZdfdZdee0   de<de0dZdfdZdee0   dZe0fdZdddee0   deee0ee0   f      dZee0   fdZdee0   dee0   dZdfdZdye0dZe0fdZdedcee0   dZee0   fdZdddgedceee0      dZee0   fdZdgedZefdZdgede0dZedpef   fdZde0dZedpef   fdZde0dZedpeeeef   f   fdZde0dZedpee   f   fdZde0dZedpee   f   fdZde0de0dZedpee   f   fdZde%jr                  dZee   fdZdee0e0f   dZdfdZd!edZefdZdeee0ee0ef   f      dZeee0ee0ef   f      fdZy# e2$ r g Z/ee0   e1d<   Y qw xY w# e2$ r i Z4ee0ee0   f   e1d<   Y mw xY w# e2$ r  e7       Z6e7e0   e1d<   Y sw xY w# e>e2f$ r eZ<e=e   e1d<   Y Lw xY w# e>e2f$ r eZBe=e   e1d<   Y w xY w# e>e2f$ r dZDdZEdZFdZJdZKdZGdZHY w xY w# e>e2f$ r dZY w xY w)z$Utility functions for agent engines.    N)metadata)AnyAsyncIteratorCallable	CoroutineDictIteratorListMappingOptionalProtocolSequenceSet	TypedDictUnion)
exceptions)types)
struct_pb2)json_format   )   
   )	TypeAlias_BUILTIN_MODULE_NAMES_PACKAGE_DISTRIBUTIONS_STDLIB_MODULE_NAMESstorage_StorageBucket_SpecifierSet)	AgentCardTransportProtocolMessageTaskIdParamsTaskQueryParams)ClientConfigClientFactoryactionsappendagent_frameworkasyncasync_streambidi_streamzagent_engine.pklcustom)z
google-adk	langchain	langgraphag2zllama-indexr.   async_queryzCoroutine[Any]async_stream_queryzAsyncIterable[Any]agent_enginea  
    Runs the Agent Engine to serve the user request.
    This will be based on the `.{method_name}(...)` of the python object that
    was passed in when creating the Agent Engine. The method will invoke the
    `{default_method_name}` API client of the python object.
    Args:
        **kwargs:
            Optional. The arguments of the `.{method_name}(...)` method.
    Returns:
        {return_type}: The response from serving the user request.
queryzdict[str, Any]zIterable[Any]cloudpicklepydanticstream_querybidi_stream_queryzdependencies.tar.gzzFailed to register API methods. Please follow the guide to register the API methods: https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#custom-methods. Error: {%s}installation_scriptsnameapi_modezrequirements.txt streama2a_extensiona2a_agent_cardwarningsmissingincompatiblezvertexai_genai.agentenginesc                   4    e Zd ZdZej
                  d        Zy)	Queryablez/Protocol for Agent Engines that can be queried.c                      y)z.Runs the Agent Engine to serve the user query.N selfkwargss     K/tmp/pip-target-z3e9_cxr/lib/python/vertexai/_genai/_agent_engines_utils.pyr5   zQueryable.query           N)__name__
__module____qualname____doc__abcabstractmethodr5   rG   rM   rK   rE   rE      s    9= =rM   rE   c                   4    e Zd ZdZej
                  d        Zy)AsyncQueryablez>Protocol for Agent Engines that can be queried asynchronously.c                      y)z=Runs the Agent Engine to serve the user query asynchronously.NrG   rH   s     rK   r2   zAsyncQueryable.async_query   rL   rM   N)rN   rO   rP   rQ   rR   rS   r2   rG   rM   rK   rU   rU      s    HL LrM   rU   c                   @    e Zd ZdZej
                  dee   fd       Zy)AsyncStreamQueryablezDProtocol for Agent Engines that can stream responses asynchronously.returnc                    K   yw)z8Asynchronously stream responses to serve the user query.NrG   rH   s     rK   r3   z'AsyncStreamQueryable.async_stream_query           N)	rN   rO   rP   rQ   rR   rS   r   r   r3   rG   rM   rK   rX   rX      s,    NGM#4F G GrM   rX   c                   @    e Zd ZdZej
                  dee   fd       Zy)StreamQueryablez5Protocol for Agent Engines that can stream responses.rY   c                      y)z)Stream responses to serve the user query.NrG   rH   s     rK   r8   zStreamQueryable.stream_query   rL   rM   N)	rN   rO   rP   rQ   rR   rS   r	   r   r8   rG   rM   rK   r^   r^      s(    ?8 8 8rM   r^   c                   ^    e Zd ZdZej
                  dej                  e   de	e   fd       Z
y)BidiStreamQueryablezBProtocol for Agent Engines that can stream requests and responses.input_queuerY   c                    K   yw)z8Stream requests and responses to serve the user queries.NrG   )rI   rb   s     rK   r9   z%BidiStreamQueryable.bidi_stream_query   r[   r\   N)rN   rO   rP   rQ   rR   rS   asyncioQueuer   r   r9   rG   rM   rK   ra   ra      s?    LG"==-G	s	G GrM   ra   c                   :    e Zd ZdZej
                  defd       Zy)	Cloneablez.Protocol for Agent Engines that can be cloned.rY   c                      y)zReturn a clone of the object.NrG   rI   s    rK   clonezCloneable.clone
  rL   rM   N)rN   rO   rP   rQ   rR   rS   r   rj   rG   rM   rK   rg   rg     s$    8,s , ,rM   rg   c                   N    e Zd ZdZej
                  dedeee	e   f   fd       Z
y)OperationRegistrablez4Protocol for agents that have registered operations.rJ   rY   c                      y)z:Register the user provided operations (modes and methods).NrG   rH   s     rK   register_operationsz(OperationRegistrable.register_operations       	rM   N)rN   rO   rP   rQ   rR   rS   r   dictstrlistrn   rG   rM   rK   rl   rl     s8    >C Dd3i4H  rM   rl   	BaseAgentADKAgentc                   \    e Zd ZU eed<   eed<   eeee   f   ed<   eee      ed<   e	ed<   y)_ModuleAgentAttributesmodule_name
agent_namern   	sys_pathsagentN)
rN   rO   rP   rq   __annotations__r   rr   r   r   _AgentEngineInterfacerG   rM   rK   rw   rw   0  s5    Oc49n--&&  rM   rw   F)totalc                   z    e Zd ZdZdddededeeee   f   deee      fdZ	dd
Z
ded	eeee   f   fdZddZy)ModuleAgentzAgent that is defined by a module and an agent name.

    This agent is instantiated by importing a module and instantiating an agent
    from that module. It also allows to register operations that are defined in
    the agent.
    N)rz   rx   ry   rn   rz   c                    ||||d| _         y)a{  Initializes a module-based agent.

        Args:
            module_name (str):
                Required. The name of the module to import.
            agent_name (str):
                Required. The name of the agent in the module to instantiate.
            register_operations (Dict[str, list[str]]):
                Required. A dictionary of API modes to a list of method names.
            sys_paths (Sequence[str]):
                Optional. The system paths to search for the module. It should
                be relative to the directory where the code will be running.
                I.e. it should correspond to the directory being passed to
                `extra_packages=...` in the create method. It will be appended
                to the system path in the sequence being specified here, and
                only be appended if it is not already in the system path.
        rx   ry   rn   rz   N)_tmpl_attrs)rI   rx   ry   rn   rz   s        rK   __init__zModuleAgent.__init__@  s    4 '$#6"	4
rM   rY   c                     t        | j                  j                  d      | j                  j                  d      | j                  j                  d      | j                  j                  d            S )zReturn a clone of the agent.rx   ry   rn   rz   r   )r   r   getri   s    rK   rj   zModuleAgent.clone`  s`    ((,,];''++L9 $ 0 0 4 45J K&&**;7	
 	
rM   rJ   c                 V    | j                   j                  d      }|t        d      |S )Nrn   zRegister operations is not set.)r   r   
ValueError)rI   rJ   reg_operationss      rK   rn   zModuleAgent.register_operationsi  s1    ))--.CD!>??rM   c           
         | j                   j                  d      }t        |t              rTddl}|D ]K  }t
        j                  j                  |      }||j                  vs1|j                  j                  |       M ddl	}|j                  | j                   j                  d            }	 |j                  |       | j                   j                  d      }	 t        ||      }	|	| j                   d
<   t#        |	d      r|	j%                          | j'                         j)                         D ]7  }
|
D ]0  }t+        |	|      }t-        | |t/        j0                  ||              2 9 y# t        $ r>}t        j                  d| j                   j                  d       d|        Y d}~d}~ww xY w# t         $ r0}t!        d| d	| j                   j                  d             |d}~ww xY w)zSets up the agent for execution of queries at runtime.

        It runs the code to import the agent from the module, and registers the
        operations of the agent.
        rz   r   Nrx   zFailed to reload module : ry   zAgent z not found in module r{   set_up)r{   	operation)r   r   
isinstancer   sysospathabspathr)   	importlibimport_modulereload	ExceptionloggerwarninggetattrAttributeErrorhasattrr   rn   values_wrap_agent_operationsetattrr   
MethodType)rI   rz   r   sys_pathabs_pathr   moduleery   r{   
operationsr   ops                rK   r   zModuleAgent.set_upo  s    $$((5	i*% .77??84388+HHOOH-.
 	(()9)9)=)=m)LM	V$
 %%)),7
	FJ/E %*!5(#LLN224;;= 	EJ' E	*)Li)9)9"d)CDE	E  	NN*4+;+;+?+?+N*OrRSQTU 	  	 $9##''679 	s0   /E, F6 ,	F354F..F36	G/?+G**G/)rY   r   )rY   N)rN   rO   rP   rQ   rq   r   rr   r   r   r   rj   r   rp   rn   r   rG   rM   rK   r   r   8  s{     .2
 
 	

 "#tCy.1
 HSM*
@
C Dd3i4H &ErM   r   c                       e Zd ZU ee   ed<   y)_RequirementsValidationActionsr)   NrN   rO   rP   r   rq   r|   rG   rM   rK   r   r     s    HrM   r   c                   .    e Zd ZU ee   ed<   ee   ed<   y)_RequirementsValidationWarningsrB   rC   Nr   rG   rM   rK   r   r     s    Xc(rM   r   c                   "    e Zd ZU eed<   eed<   y)_RequirementsValidationResultrA   r(   N)rN   rO   rP   r   r|   r   rG   rM   rK   r   r     s    --++rM   r   c                        e Zd ZdededefdZy)GetOperationFunctionoperation_namerJ   rY   c                     y NrG   rI   r   rJ   s      rK   __call__zGetOperationFunction.__call__  ro   rM   NrN   rO   rP   rq   r   AgentEngineOperationUnionr   rG   rM   rK   r   r         !$03	"rM   r   c                        e Zd ZdededefdZy)GetAsyncOperationFunctionr   rJ   rY   c                   K   y wr   rG   r   s      rK   r   z"GetAsyncOperationFunction.__call__  s      	r\   Nr   rG   rM   rK   r   r     r   rM   r   r   resource_namerY   c                    |s| st        d      |r8t        j                  d|      }|r|j                  d      S t        d| d      | st        d      t        j                  d|       }|r|j                  d      S t        d|  d      )	zAReturns reasoning engine ID from operation name or resource name.z0Resource name or operation name cannot be empty.z9^projects/[^/]+/locations/[^/]+/reasoningEngines/([^/]+)$r   z9Failed to parse reasoning engine ID from resource name: ``zOperation name cannot be empty.zJ^projects/[^/]+/locations/[^/]+/reasoningEngines/([^/]+)/operations/[^/]+$z:Failed to parse reasoning engine ID from operation name: `)r   rematchgroup)r   r   r   s      rK   _get_reasoning_engine_idr     s    KLLH
 ;;q>!!?!% 
 :;;HHUE {{1~
	1	 rM   r   )poll_interval_secondsget_operation_fnr   c                    K    ||        d{   }|j                   sEt        j                  |       d{     ||j                         d{   }|j                   sE|S 7 W7 07 w)aF  Waits for the operation for creating an agent engine to complete.

    Args:
        operation_name (str):
            Required. The name of the operation for creating the Agent Engine.
        poll_interval_seconds (float):
            The number of seconds to wait between each poll.
        get_operation_fn (Callable[[str], Awaitable[Any]]):
            Optional. The async function to use for getting the operation. If not
            provided, `self._get_agent_operation` will be used.

    Returns:
        The operation that has completed (i.e. `operation.done==True`).
    r   N)donerd   sleepr;   r   r   r   r   s       rK   _await_async_operationr     s_     ( 'nEEInnmm1222*)..II	 nn  F2Is7   A-A'(A-A)A-A+A-%A-)A-+A-c                      ||       }|j                   s5t        j                  |        ||j                        }|j                   s5|S )a5  Waits for the operation for creating an agent engine to complete.

    Args:
        operation_name (str):
            Required. The name of the operation for creating the Agent Engine.
        poll_interval_seconds (float):
            The number of seconds to wait between each poll.
        get_operation_fn (Callable[[str], Any]):
            Optional. The function to use for getting the operation. If not
            provided, `self._get_agent_operation` will be used.

    Returns:
        The operation that has completed (i.e. `operation.done==True`).
    r   )r   timer   r;   r   s       rK   _await_operationr     sA    ( !?Inn

()$INNC	 nn rM   )required_packagesrequirementsconstraintsr   c           
      >   t               }|t        }t        t        t	               t	                     t        t	                           }t        |t              rt        |      }| j                         D ]  \  }}||vrH|t           t           j                  |       ||v r$|t           t           j                  | d|        R|sU||   }|s]|j                  |      |vsq|t           t            j                  | d| dt#        |       d        |S )a  Compares the requirements with the constraints.

    Args:
        requirements (Mapping[str, str]):
            Required. The packages (and their versions) to compare with the constraints.
            This is assumed to be the result of `scan_requirements`.
        constraints (Union[Sequence[str], Mapping[str, SpecifierSet]]):
            Required. The package constraints to compare against. This is assumed
            to be the result of `parse_constraints`.
        required_packages (Iterator[str]):
            Optional. The set of packages that are required to be in the
            constraints. It defaults to the set of packages that are required
            for deployment on Agent Engine.

    Returns:
        dict[str, dict[str, Any]]: The comparison result as a dictionary containing:
            * warnings:
                * missing: The set of packages that are not in the constraints.
                * incompatible: The set of packages that are in the constraints
                    but have versions that are not in the constraint specifier.
            * actions:
                * append: The set of packages that are not in the constraints
                    but should be appended to the constraints.
    )rB   rC   )r)   )rA   r(   r   z==z (required: ))"_import_packaging_version_or_raise_DEFAULT_REQUIRED_PACKAGESr   r   setr   r   rr   _parse_constraintsitems_WARNINGS_KEY_WARNING_MISSINGadd_ACTIONS_KEY_ACTION_APPENDVersion_WARNING_INCOMPATIBLErq   )r   r   r   packaging_versionresultpackagepackage_versionpackage_specifiers           rK   _compare_requirementsr     s+   < ;< 6*0SUS.ce<F +t$([A$0$6$6$8  +%=!"2377@++|$^488ir/!23  +G 4$ ((9ARR}%&;<@@ir/!2,sCT?U>VVWX  MrM   r{   r   c           	      `   t        | t              r!| j                         } 	 | j                          g }|j                         D ]  \  }}|D ]  }t        | |      st        d| d      t        | |      }	 t        ||      }t        |      }	||	t        <   t        | d      r!t        | d      j                         |	t        <   |j!                  |	         |S # t        $ r}t        d|  d|       |d}~ww xY w# t        $ r%}t        j                  d| d|        Y d}~d}~ww xY w)	a}  Generates a ReasoningEngineSpec based on the registered operations.

    Args:
        agent: The AgentEngine instance.
        operations: A dictionary of API modes and method names.

    Returns:
        A list of ReasoningEngineSpec.ClassMethod messages.

    Raises:
        ValueError: If a method defined in `register_operations` is not found on
        the AgentEngine.
    zFailed to set up agent r   NzMethod `z6` defined in `register_operations` not found on agent.)schema_namezfailed to generate schema for 
agent_card)r   r   rj   r   r   r   r   r   r   _generate_schemar   r   	_to_proto_MODE_KEY_IN_SCHEMAmodel_dump_json_A2A_AGENT_CARDr)   )
r{   r   r   class_methods_specmodemethod_namesmethod_namemethodschema_dictclass_methods
             rK   %_generate_class_methods_spec_or_raiser   N  sZ   $ %% #[[]	LLLN (..0 4l' 	4K5+. {m ,+ + 
 UK0F.v;O
 %[1L04L,-ul+07<1!/# _- %%l3)	44. 5  	L6ugRsCD!K	L  !?}BqcRSs/   C 7C?	C<%C77C<?	D-D((D-class_methodsc                 >    | D cg c]  }t        |       c}S c c}w )zWConverts a list of class methods to a list of ReasoningEngineSpec.ClassMethod messages.)r   )r   r   s     rK   $_class_methods_to_class_methods_specr     s     9FFIl#FFFs   paramc                 $   | j                   t        j                  j                  k(  rydt	        | j                         v ryt        | j                   t              ryt               }	 |j                  | j                          y# t        $ r Y yw xY w)z1Checks if the parameter is pydantic serializable.T
ForwardRefF)

annotationinspect	Parameteremptyreprr   rq   _import_pydantic_or_raiseTypeAdapterr   )r   r7   s     rK   _is_pydantic_serializabler    s     7,,222tE,,--%""C((*HU--. s   'B 	BB)r   descriptionsrequiredf.r   r  r  c                :   t               }t        t        j                  |       j                        }|j                         D ci c]  \  }}|j                  t        j                  j                  t        j                  j                  t        j                  j                  fv r|j                  t        j                  k7  r~t        |      rs||j                  t        j                  j                  k7  r#dt!        |j                        vr|j                  nt"        |j%                  |j'                  |d            f }}} |j(                  | j*                  fi |j-                         }	|	j/                  dd       |	j'                  di       j                         D ]  \  }}
|
j/                  dd       ||   j                  }t1        j2                  |      t4        u sCt7        d      t1        j8                  |      v sd|
j/                  dg       D ]"  }|j'                  d      }|s|d	k7  s||
d<    n d
|
d<    |r||	d<   n|D cg c]  }||   j:                  t        j                  j                  k(  r^||   j                  t        j                  j                  t        j                  j                  t        j                  j                  fv r| c}|	d<   t        | j*                  | j<                  |	      }|r||d<   |S c c}}w c c}w )a/  Generates the OpenAPI Schema for a callable object.

    Only positional and keyword arguments of the function `f` will be supported
    in the OpenAPI Schema that is generated. I.e. `*args` and `**kwargs` will
    not be present in the OpenAPI schema returned from this function. For those
    cases, you can either include it in the docstring for `f`, or modify the
    OpenAPI schema returned from this function to include additional arguments.

    Args:
        f (Callable):
            Required. The function to generate an OpenAPI Schema for.
        schema_name (str):
            Optional. The name for the OpenAPI schema. If unspecified, the name
            of the Callable will be used.
        descriptions (Mapping[str, str]):
            Optional. A `{name: description}` mapping for annotating input
            arguments of the function with user-provided descriptions. It
            defaults to an empty dictionary (i.e. there will not be any
            description for any of the inputs).
        required (Sequence[str]):
            Optional. For the user to specify the set of required arguments in
            function calls to `f`. If specified, it will be automatically
            inferred from `f`.

    Returns:
        dict[str, Any]: The OpenAPI Schema for the function `f` in JSON format.
    r   N)descriptiontitler=   
propertiesanyOftypenullTnullabler  )r;   r  
parametersr;   )r   rp   r   	signaturer  r   kindr   POSITIONAL_OR_KEYWORDKEYWORD_ONLYPOSITIONAL_ONLYr   rd   re   r  r   r   r   Fieldr   create_modelrN   schemapoptyping
get_originr   r
  get_argsdefaultrQ   )r  r   r  r  r7   defaultsr;   r   fields_dictr  function_argr   r  schema_typeks                  rK   r   r     s   D )*HG%%a(334H* $>>+)( D%::33**--

 -2KE2R; 	
 ##w'8'8'>'>> U-=-=(>>    NN ),,T48  
 	
K @ '&&qzzA[AHHJJ
 NN7B(nn\2>DDF ,l"%d^..

 Z(E1d4jFOOE
 7
 '**7B7 $jj0;&#8+6L(	
 (,L$',* !)
:
 "
##w'8'8'>'>>QK$$%%;;%%22%%55	 "

: qzzqyyZPF$vMa@"
s   C>LBLc                 >   | "| t         v rt        j                  d|         | S t        |t              rDt        |t              }|2t        |t              r"|t         v rt        j                  d|        |S t        j                  d|  dt         d       t        S )a  Gets the agent framework to use.

    The agent framework is determined in the following order of priority:
    1. The `agent_framework` passed to this function.
    2. The `agent_framework` attribute on the `agent` object.
    3. The default framework, "custom".

    Args:
        agent_framework (str):
            The agent framework provided by the user.
        agent (_AgentEngineInterface):
            The agent engine instance.

    Returns:
        str: The name of the agent framework to use.
    zUsing agent framework: zThe provided agent framework z! is not supported. Defaulting to .)	_SUPPORTED_AGENT_FRAMEWORKSr   infor   _AGENT_FRAMEWORK_ATTRr   r   rq   _DEFAULT_AGENT_FRAMEWORK)r*   r{   agent_framework_attrs      rK   _get_agent_frameworkr'    s    * ":U'U-o->?@u+,&u.CD ,/5$(CCKK12F1GHI''
KK
''8 9231	6 $#rM   )credentialsprojectlocationstaging_bucketr(  c                 l   t               } |j                  | |      }|j                  dd      }	 |j                  |      }t        j                  d|        |S # t        j                  $ rC |j                  |      }|j                  ||      }t        j                  d| d|       Y |S w xY w)zGets or creates the GCS bucket.)r)  r(  gs://r=   zUsing bucket )r*  zCreating bucket z in location=)
_import_cloud_storage_or_raiseClientreplace
get_bucketr   r#  r   NotFoundbucketcreate_bucket)r)  r*  r+  r(  r   storage_client
gcs_bucket
new_buckets           rK   _get_gcs_bucketr8  =  s     -.G#W^^GMN#++GR8NH#..~>
mN#345
 	  H#**>:
#11*x1P
&~&6n8+FG	Hs   )A AB32B3c                 v   t        | t              r| j                         S i }t        | t              rt        g|t
        <   t        | t              rt        g|t        <   t        | t              rt        g|t        <   t        | t              rt        g|t        <   t        | t              rt         g|t"        <   |S )z2Retrieves registered operations for a AgentEngine.)r   rl   rn   rE   _DEFAULT_METHOD_NAME_STANDARD_API_MODErU   _DEFAULT_ASYNC_METHOD_NAME_ASYNC_API_MODEr^   _DEFAULT_STREAM_METHOD_NAME_STREAM_API_MODErX   !_DEFAULT_ASYNC_STREAM_METHOD_NAME_ASYNC_STREAM_API_MODEra    _DEFAULT_BIDI_STREAM_METHOD_NAME_BIDI_STREAM_API_MODE)r{   r   s     rK   _get_registered_operationsrD  R  s    
 %-.((**J%#*>)?
%&%('A&B
?#%)(C'D
#$%-..O-P
)*%,--M,N
()rM   c                  J    	 ddl } | S # t        $ r}t        d      |d}~ww xY w)z'Tries to import the cloudpickle module.r   Nz_cloudpickle is not installed. Please call 'pip install google-cloud-aiplatform[agent_engines]'.)r6   ImportError)r6   r   s     rK   _import_cloudpickle_or_raiserG  h  s<       D
 	s    	""c                  N    	 ddl m}  | S # t        $ r}t        d      |d}~ww xY w)z)Tries to import the Cloud Storage module.r   r   zaCloud Storage is not installed. Please call 'pip install google-cloud-aiplatform[agent_engines]'.N)google.cloudr   rF  )r   r   s     rK   r.  r.  t  s;    ( N  D
 	   
 	$$c                  N    	 ddl m}  | S # t        $ r}t        d      |d}~ww xY w)2Tries to import the packaging.requirements module.r   r   zjpackaging.requirements is not installed. Please call 'pip install google-cloud-aiplatform[agent_engines]'.N)	packagingr   rF  )r   r   s     rK   '_import_packaging_requirements_or_raiserO    s<    *   D
 	rJ  c                  N    	 ddl m}  | S # t        $ r}t        d      |d}~ww xY w)rL  r   )versionzepackaging.version is not installed. Please call 'pip install google-cloud-aiplatform[agent_engines]'.N)rN  rQ  rF  )rQ  r   s     rK   r   r     s;    % N  D
 	rJ  c                      	 ddl } | j                  }| S # t        $ r
 ddl m}  Y | S t        $ r}t	        d      |d}~ww xY w)z$Tries to import the pydantic module.r   N)v1z\pydantic is not installed. Please call 'pip install google-cloud-aiplatform[agent_engines]'.)r7   r  r   rS  rF  )r7   _r   s      rK   r   r     sX    
NN O  ,+ O  D
 	s    ??:?c                 L   t               }i }| D ]a  }	 |j                  d      rt        j                  j	                  |      }|j                  |      }|j                  xs d||j                  <   c |S # t        $ r%}t        j                  d| d|        Y d}~d}~ww xY w)aA  Parses a list of constraints into a dict of requirements.

    Args:
        constraints (list[str]):
            Required. The list of package requirements to parse. This is assumed
            to come from the `requirements.txt` file.

    Returns:
        dict[str, SpecifierSet]: The specifiers for each package.
    z.whlzFailed to parse constraint: . Exception: N)rO  endswithr   r   basenameRequirementr   r   r   	specifierr;   )r   r   r   
constraintrequirementr   s         rK   r   r     s     ;<L13F! A
	""6*WW--j9
&22:>K $/#8#8#@D{ A M	  	NN9*]STRUVW	s   AA55	B#>BB#extra_packagesgcs_dir_namec                     | yt        ||||      }t        | ||       |t        |||       |t        |||       yy)a  Prepares the agent engine for creation or updates in Vertex AI.

    This involves packaging and uploading artifacts to Cloud Storage. Note that
    1. This does not actually update the Agent Engine in Vertex AI.
    2. This will only generate and upload a pickled object if specified.
    3. This will only generate and upload the dependencies.tar.gz file if
    extra_packages is non-empty.

    Args:
        agent: The agent engine to be prepared.
        requirements (Sequence[str]): The set of PyPI dependencies needed.
        extra_packages (Sequence[str]): The set of extra user-provided packages.
        project (str): The project for the staging bucket.
        location (str): The location for the staging bucket.
        staging_bucket (str): The staging bucket name in the form "gs://...".
        gcs_dir_name (str): The GCS bucket directory under `staging_bucket` to use
          for staging the artifacts needed.
        credentials: The credentials to use for the storage client.
    N)r)  r*  r+  r(  )r{   r6  r^  )r   r6  r^  )r]  r6  r^  )r8  _upload_agent_engine_upload_requirements_upload_extra_packages)	r{   r   r]  r)  r*  r+  r^  r(  r6  s	            rK   _preparerc    sl    < } %	J !
 %!%	

 !)!%	
 "rM   )wrap_operation_fnrd  c                 .   | j                         }|sy|D ]  }t        |vrt        d| dt         d      |j                  t              }|t        k(  rAt
        |vrt        d| dt
         d      |j                  t
              }t        |t              st        dt
         d|       |j                  dt        j                  |t        j                  |t              t        j                  |t              	            }t        t        t         t"        t$        t&        t(        t*        t,        t.        i}t        |t0              r
||v r||   }nK||v r||   }nAd
j3                  d t5        |j7                               D              }	t        d| d|	 d      |t,        k(  r |j                  t8              }
 |||
      }n	 ||      }||_        |rt        |t              r||_        t?        | |tA        jB                  ||               y)a  Registers Agent Engine API methods based on operation schemas.

    This function iterates through operation schemas provided by the
    `agent_engine`.  Each schema defines an API mode and method name.
    It dynamically creates and registers methods on the `agent_engine`
    to handle API calls based on the specified API mode.
    Currently, only standard API mode `` is supported.

    Args:
        agent_engine: The AgentEngine to augment with API methods.
        wrap_operation_fn: A dictionary of API modes and method wrapping
            functions.

    Raises:
        ValueError: If the API mode is not supported or if the operation schema
        is missing any required fields (e.g. `api_mode` or `name`).
    NzOperation schema z does not contain an `z` field.z does not contain a `z-Operation schema has a non-string value for `z`: r  )r   default_method_namereturn_typez, c              3   (   K   | ]
  }d | d   yw)r   NrG   ).0r   s     rK   	<genexpr>z1_register_api_methods_or_raise.<locals>.<genexpr>H  s      , $!D6,s   zUnsupported api mode: `z`, Supported modes are: r!  )r   r   )r   )"operation_schemasr   r   r   rC  _METHOD_NAME_KEY_IN_SCHEMAr   rq   "_DEFAULT_METHOD_DOCSTRING_TEMPLATEformat_DEFAULT_METHOD_NAME_MAPr:  _DEFAULT_METHOD_RETURN_TYPE_MAP_DEFAULT_METHOD_RETURN_TYPEr;  _wrap_query_operationr=  _wrap_async_query_operationr?  _wrap_stream_query_operationrA  "_wrap_async_stream_query_operation_A2A_EXTENSION_MODE_wrap_a2a_operationrp   joinsortedkeysr   rN   rQ   r   r   r   )r4   rd  rk  operation_schemar<   r   method_description_wrap_operation_map_wrap_operationsupported_api_modesr   r   s               rK   _register_api_methods_or_raiser    s_   0 %668- CS&66#$4#5 6  34H>  $''(;<,,%-==#$4#5 69:(D  '**+EF+s+/0K=B  .11.55'$<$@$@2% <??/ 6 	
  58:"$F!4
 '.8?P3P/9O,,1(;O"&)) ,(./B/G/G/I(J, # )( 4))<(=Q@  **)--o>J$'JF %=F%*-?"E/FNk5+;+;FL+QRGCSrM   )ignore_modulespackage_distributionsinspect_getmembers_kwargsobjr  r  r  c                    |t         }|t        }t        t              }|xs i }t	        j
                  | fi |D ]{  \  }}|r!t	        j                  |      st        |d      s*|j                  xs dj                  d      d   }|sO||vsT|j                  |g       D ]  }|j                  |        } |D ci c]  }|t        j                  |       c}S c c}w )a  Scans the object for modules and returns the requirements discovered.

    This is not a comprehensive scan of the object, and only detects for common
    cases based on the members of the object returned by `dir(obj)`.

    Args:
        obj (Any):
            Required. The object to scan for package requirements.
        ignore_modules (Sequence[str]):
            Optional. The set of modules to ignore. It defaults to the set of
            built-in and stdlib modules.
        package_distributions (Mapping[str, Sequence[str]]):
            Optional. The mapping of module names to the set of packages that
            contain them. It defaults to the set of packages from
            `importlib_metadata.packages_distributions()`.
        inspect_getmembers_kwargs (Mapping[str, Any]):
            Optional. The keyword arguments to pass to `inspect.getmembers`. It
            defaults to an empty dictionary.

    Returns:
        Sequence[str]: The list of requirements that were discovered.
    rO   r=   r!  r   )_BASE_MODULESr   r   r   r   
getmembers	isbuiltinr   rO   splitr   r   importlib_metadatarQ  )	r  r  r  r  modules_foundrT  attrrx   r   s	            rK   _scan_requirementsr  ^  s    : &$ 623M 9 ?R%%cG-FG *4w((.gdL6Q,"33C8;;n</33KD *!!&)** FSS6F&..v66SSSs   >Cmessagec                     	 t        j                  t        j                  | j                  d            }|S # t
        $ r. t        j                  t        j                  | d            }Y |S w xY w)a  Converts the contents of the protobuf message to JSON format.

    Args:
        message (proto.Message):
            Required. The proto message to be converted to a JSON dictionary.

    Returns:
        dict[str, Any]: A dictionary containing the contents of the proto.
    T)preserving_proto_field_name)jsonloadsr   MessageToJson_pbr   )r  r   s     rK   _to_dictr    sn    
!%%%,0"
 M  
!%%%,0"
 M
s   48 3A/.A/c                    |t        j                         }t        | t        j                  t         j                  f      r| S 	 t        j                  | |j                         |S # t        $ r t        j                  | |       Y |S w xY w)a<  Parses a JSON-like object into a message.

    If the object is already a message, this will return the object as-is. If
    the object is a JSON Dict, this will parse and merge the object into the
    message.

    Args:
        obj (Union[dict[str, Any], proto.Message]):
            Required. The object to convert to a proto message.
        message (proto.Message):
            Optional. A protocol buffer message to merge the obj into. It
            defaults to Struct() if unspecified.

    Returns:
        proto.Message: The same message passed as argument.
    )	r   Structr   protor#   r   	ParseDictr  r   )r  r  s     rK   r   r     s{    ( ##%#z'8'89:
,c7;;/ N  ,c7+N,s    A& &B	B	r6  c                    t               }|j                  | dt               }|j                  d      5 }	 |j	                  | |       	 ddd       |j                  d      5 }	 |j                  |      }	 ddd       d	|j                   d| }	t        j                  d
|	 dt                y# t
        $ r}d}t        d| d      |d}~ww xY w# 1 sw Y   xY w# t
        $ r}t        d      |d}~ww xY w# 1 sw Y   xY w)z Uploads the agent engine to GCS./wbzkhttps://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/develop/custom#deployment-considerationsz(Failed to serialize agent engine. Visit z for details.Nrbz,Agent engine serialized to an invalid formatr-  z	Wrote to )rG  blob_BLOB_FILENAMEopendumpr   	TypeErrorloadr;   r   r#  )
r{   r6  r^  r6   r  r  r   urlrT  dir_names
             rK   r`  r`    s#    /0K??l^1^,<=>D	4 A	UA& 
4 SA	S  #AS
 z'q7H
KK)H:Q~&678  	C:3%}M	   	SJKQRR	SS SsR   CB2$C>&C!2	C;CCCC!	C;*C66C;;C>>Dc                     |j                  | dt               }|j                  dj                  |              d|j                   d| }t
        j                  d| dt                y)z%Uploads the requirements file to GCS.r  
r-  Writing to N)r  _REQUIREMENTS_FILEupload_from_stringrx  r;   r   r#  )r   r6  r^  r  r  s        rK   ra  ra    sh     ??l^1-?,@ABDDIIl34z'q7H
KK+hZq);(<=>rM   c                    t         j                  d       t        j                         }t	        j
                  |d      5 }| D ]  }|j                  |        	 ddd       |j                  d       |j                  | dt               }|j                  |j                                d|j                   d| }t         j                  d| dt                y# 1 sw Y   xY w)	zUploads extra packages to GCS.z,Creating in-memory tarfile of extra_packagesw|gzfileobjr   Nr   r  r-  r  )r   r#  ioBytesIOtarfiler  r   seekr  _EXTRA_PACKAGES_FILEr  readr;   )r]  r6  r^  tar_fileobjtarfiler  r  s           rK   rb  rb    s     KK>?**,K	k	7 3" 	DGGDM	 Q??l^1-A,BCDDK,,./z'q7H
KK+hZq)=(>?@ s   CC(source_packagesc           	      z   t         j                  d       t        j                         }t        j
                  j                  t	        j                               }t        j                  |d      5 }| D ]k  }t        j
                  j                  |      }||k7  r4|j                  |t        j                  z         st        d| d| d      |j                  |       m 	 ddd       |j                  d       |j                         }t!        j"                  |      j%                  d	      S # 1 sw Y   NxY w)
z:Creates a base64 encoded tarball from the source packages.z-Creating in-memory tarfile of source_packagesr  r  zFile path 'z$' is outside the project directory 'z'.Nr   zutf-8)r   r#  r  r  r   r   realpathgetcwdr  r  
startswithsepr   r   r  r  base64	b64encodedecode)r  r  project_dirr  r  real_file_pathtarball_bytess          rK   _create_base64_encoded_tarballr     s   
 KK?@**,K''""299;/K	k	7 
3# 		DWW--d3N,^5N5Nbff$6 !!$ (#}B(  GGDM		
 Q$$&MM*11'::
 
s   2A1D11D:)build_optionspackagesr  c                     | xs g } |rt         |v rt        |t            |        | D ]/  }t        j                  j	                  |      r#t        d|       | S )z Tries to validates the packages.)script_pathsr  z)Package specified but not found: package=)_INSTALLATION_SUBDIR'_validate_installation_scripts_or_raiser   r   existsFileNotFoundError)r  r  r   s      rK   _validate_packages_or_raiser    si     ~2H->/&';<	
  Tww~~g&#&Pz$RSST OrM   r  c           
         | D ]  }|j                  t              s=t        j                  d| dt         dt         d       t	        d| dt         d      ||vsZt        j                  d| d       t	        d| d	       |D ]D  }|j                  t              s|| vst        j                  d
| d       t	        d
| d       y)a  Validates the installation scripts' path explicitly provided by the user.

    Args:
        script_paths (Sequence[str]):
            Required. The paths to the installation scripts.
        packages (Sequence[str]):
            Required. The user-provided packages.

    Raises:
        ValueError: If a user-defined script is not under the expected
            subdirectory, or not in `packages`, or if a package is
            in the installation scripts subdirectory, but is not specified as an
            installation script.
    z"User-defined installation script 'z' is not in the expected 'z(' subdirectory. Ensure it is placed in 'z4' within your 'extra_packages' or 'source_packages'.zRequired installation script 'z' is not under ''zo' is not in 'extra_packages' or 'source_packages'. Ensure it is added to 'extra_packages' or 'source_packages'.z:' does not exist in 'extra_packages' or 'source_packages'.z	Package 'z' is in the installation scripts subdirectory, but is not specified as an installation script in `build_options`. Ensure it is added to installation_scripts for automatic execution.zq' is in the installation scripts subdirectory, but is not specified as an installation script in `build_options`.N)r  r  r   r   r   )r  r  script_pathr   s       rK   r  r  *  s3   & $ %%&:;NN4[M B!!5 6 7++?*@ A9: 0 >!!5 6a9 
 h&NN4[M B9 :
 4[M BK L '0  23|8SNNG9 %' ' G9 %- -  rM   c                 `    | st        d      | j                  d      st        d| d      | S )z%Tries to validate the staging bucket.zHPlease provide a `staging_bucket` in `client.agent_engines.create(...)`.r-  zstaging_bucket=z must start with `gs://`)r   r  )r+  s    rK   !_validate_staging_bucket_or_raiser  f  sA    V
 	
 $$W-ON,,DEFFrM   c                 $   |j                         }	 t        |       }t        j                  d|        t	        |      }t        ||      }|d   j                         D ]#  \  }}|s	t        j                  d| d|        % |d   j                         D ]B  \  }}|s	|t        k(  s|D ]  }	|j                  |	        t        j                  d	|        D 	 |S # t        $ r#}
t        j                  d
|
        Y d}
~
|S d}
~
ww xY w)z6Compiles the requirements into a list of requirements.)r  z'Identified the following requirements: r   )r   r   rA   zThe following requirements are r   r(   z)The following requirements are appended: z Failed to compile requirements: N)copyr  r   r#  r   r   r   r   r   r)   r   )r  r   current_requirementsr   missing_requirementswarning_typerA   action_typer(   actionr   s              rK   _validate_requirements_or_warnr  q  s.     $$&L?1c:=>R=STU(\B4-# 
 ';:&F&L&L&N 	"L(5l^2hZP	
 %9$C$I$I$K 	S K;.8% 0F ''/0GyQR		S   ?9!=>>?s*   AC# +8C# $	C# .2C# #	D,D

DrM  c                    |g }nst        |t              rc	 t        j                  d|       t	        |      5 }|j                         j                         }t        j                  d|        ddd       t        | |      }t        j                  d|        |S # 1 sw Y   0xY w# t        $ r}t        d|      |d}~ww xY w)z#Tries to validate the requirements.Nz'Reading requirements from requirements=zRead the following lines: z.Failed to read requirements from requirements=)r  r   z The final list of requirements: )	r   rq   r   r#  r  r  
splitlinesIOErrorr  )r{   r   r  errs       rK   _validate_requirements_or_raiser    s     	L#	&	XKKB\ODEl# Iq vvx2248GHI
 2!L KK2<.ABI I  	XKl_MNTWW	Xs.   #B, 7B 1B,  B)%B, ,	C	5CC	c                    	 ddl m} t        | |      r-t        j	                  d       ddlm} |j                  |       } t        | t              xr t        | j                        }t        | t              xr t        | j                        }t        | t              xr t        | j                        }t        | t               xr t        | j"                        }t        | t$              xr t        | j&                        }t        | t(              xr t        | j*                        }|s|s|s|s|s|st-        d      |r 	 t/        j0                  t3        | d             |r 	 t/        j0                  t3        | d
             |r 	 t/        j0                  t3        | d             |r 	 t/        j0                  t3        | d             |r 	 t/        j0                  t3        | d             |r 	 t/        j0                  t3        | d             t        | t6              r| j9                         } | S # t        $ r Y w xY w# t4        $ r}	t5        d      |	d	}	~	ww xY w# t4        $ r}	t5        d      |	d	}	~	ww xY w# t4        $ r}	t5        d      |	d	}	~	ww xY w# t4        $ r}	t5        d      |	d	}	~	ww xY w# t4        $ r}	t5        d      |	d	}	~	ww xY w# t4        $ r}	t5        d      |	d	}	~	ww xY w)a  Tries to validate the agent engine.

    The agent engine must have one of the following:
    * a callable method named `query`
    * a callable method named `stream_query`
    * a callable method named `async_stream_query`
    * a callable method named `bidi_stream_query`
    * a callable method named `register_operations`

    Args:
        agent: The agent to be validated.

    Returns:
        The validated agent engine.

    Raises:
        TypeError: If `agent_engine` has no callable method named `query`,
        `stream_query` or `register_operations`.
        ValueError: If `agent_engine` has an invalid `query`, `stream_query` or
        `register_operations` signature.
    r   rs   z4Deploying google.adk.agents.Agent as an application.)agent_engines)r{   zagent_engine has none of the following callable methods: `query`, `async_query`, `stream_query`, `async_stream_query`, `bidi_stream_query`, or `register_operations`.r5   zbInvalid query signature. This might be due to a missing `self` argument in the agent.query method.Nr2   znInvalid async_query signature. This might be due to a missing `self` argument in the agent.async_query method.r8   zpInvalid stream_query signature. This might be due to a missing `self` argument in the agent.stream_query method.r3   z}Invalid async_stream_query signature. This might be due to a  missing `self` argument in the agent.async_stream_query method.r9   z{Invalid bidi_stream_query signature. This might be due to a  missing `self` argument in the agent.bidi_stream_query method.rn   z~Invalid register_operations signature. This might be due to a missing `self` argument in the agent.register_operations method.)google.adk.agentsrt   r   r   r#  vertexair  AdkAppr   rE   callabler5   rU   r2   r^   r8   rX   r3   ra   r9   rl   rn   r  r   r  r   r   rg   rj   )
r{   rt   r  is_queryableis_async_queryableis_stream_queryableis_async_stream_queryableis_bidi_stream_queryableis_operation_registrabler  s
             rK   _validate_agent_or_raiser    s   2	/eY'KKNO.!((u(5E eY/IHU[[4IL#E>: x@ %UO< B !+52F G !H  M  *%1DE  (K  *%1EF  8!!L
 	##$=
 	
 	geW56 	ge];< 	ge^<= !	ge-ABC  	ge-@AB  	ge-BCD %#Lu  H  	= 	  	C 	  	E 	  	S 	  	R 	  	S 	s   ?H0 I  'I 	I: +J J4 /K 0	H=<H= 	I	II	I7&I22I7:	JJJ	J1 J,,J14	K=K		K	K+K&&K+r   c                 d    dt         ffd}|_        t        |       j                  |_        |S )zAWraps an agent operation into a method (works for all API modes).rY   c                     | j                   j                  d      s| j                           t        | j                   d         di |S )Nr{   rG   )r   r   r   r   )rI   rJ   r   s     rK   _methodz&_wrap_agent_operation.<locals>._method(  sB    ##G,KKM<wt''0)<FvFFrM   )r   rN   r   rQ   )r{   r   r  s    ` rK   r   r   %  s4    G3 G
 !GeY/77GONrM   r   c                 @     dt         j                  dt        f fd}|S )a  Wraps an Agent Engine method, creating a callable for `query` API.

    This function creates a callable object that executes the specified
    Agent Engine method using the `query` API.  It handles the creation of
    the API request and the processing of the API response.

    Args:
        method_name: The name of the Agent Engine method to call.
        doc: Documentation string for the method.

    Returns:
        A callable object that executes the method on the Agent Engine via
        the `query` API.
    rI   rY   c                     | j                   st        d      | j                  st        d      | j                   j                  | j                  j                  |dd      }|j
                  S )Napi_client is not initialized. api_resource is not initialized.Tr   inputinclude_all_fieldsr;   config)
api_clientr   api_resource_queryr;   outputrI   rJ   responser   s      rK   r  z&_wrap_query_operation.<locals>._methodB  sm    =>>  ?@@??))""'' +&* * 
 rM   )genai_typesAgentEnginer   r   r  s   ` rK   rr  rr  2  s#     k-- C  NrM   c           
           dt         j                  dt        dt        t        t        t        t        f   t        f   f fd}|S )a  Wraps an Agent Engine method, creating an async callable for `query` API.

    This function creates a callable object that executes the specified
    Agent Engine method asynchronously using the `query` API. It handles the
    creation of the API request and the processing of the API response.

    Args:
        method_name: The name of the Agent Engine method to call.
        doc: Documentation string for the method.

    Returns:
        A callable object that executes the method on the Agent Engine via
        the `query` API.
    rI   rJ   rY   c                    K   | j                   st        d      | j                  st        d      | j                   j                  | j                  j                  |dd       d {   }|j
                  S 7 w)Nz$api_async_client is not initialized.r  Tr  r  )api_async_clientr   r  r  r;   r  r  s      rK   r  z,_wrap_async_query_operation.<locals>._methodf  s      $$CDD  ?@@..55""'' +&* 6 
 
 
s   A'A=*A;+A=)r  r   r   r   r   r  s   ` rK   rs  rs  T  sB    $%%14	yc3',	-" NrM   c                 N     dt         j                  dt        t           f fd}|S )a  Wraps an Agent Engine method, creating a callable for `stream_query` API.

    This function creates a callable object that executes the specified
    Agent Engine method using the `stream_query` API.  It handles the
    creation of the API request and the processing of the API response.

    Args:
        method_name: The name of the Agent Engine method to call.
        doc: Documentation string for the method.

    Returns:
        A callable object that executes the method on the Agent Engine via
        the `stream_query` API.
    rI   rY   c              ;     K   | j                   st        d      | j                  st        d      | j                   j                  | j                  j                  |dd      D ]  }t        |      D ]	  }||   y wNr  r  Tr  r  )http_response)r  r   r  _stream_queryr;   _yield_parsed_jsonrI   rJ   r  liner   s       rK   r  z-_wrap_stream_query_operation.<locals>._method  s     =>>  ?@@!__::""'' +&* ; 
 
	M +G #J
	s   A8B<	B)r  r   r	   r   r  s   ` rK   rt  rt  z  s'     k-- HSM " NrM   c                 N     dt         j                  dt        t           f fd}|S )a$  Wraps an Agent Engine method, creating an async callable for `stream_query` API.

    This function creates a callable object that executes the specified
    Agent Engine method using the `stream_query` API.  It handles the
    creation of the API request and the processing of the API response.

    Args:
        method_name: The name of the Agent Engine method to call.
        doc: Documentation string for the method.

    Returns:
        A callable object that executes the method on the Agent Engine via
        the `stream_query` API.
    rI   rY   c                   K   | j                   st        d      | j                  st        d      | j                   j                  | j                  j                  |dd      2 3 d {   }t        |      D ]
  }||  #7 6 y wr  )r  r   r  _async_stream_queryr;   r
  r  s       rK   r  z3_wrap_async_stream_query_operation.<locals>._method  s     =>>  ?@@#'??#F#F""'' +&* $G $
 
	 
	- +G #J
	 $
s0   A$B'B+B
,B/BB
BB)r  r   r   r   r  s   ` rK   ru  ru    s)    $K33 -PSBT " NrM   r   c                 $     dt         f fd}|S )a  Wraps an Agent Engine method, creating a callable for A2A API.

    Args:
        method_name: The name of the Agent Engine method to call.
        agent_card: The agent card to use for the A2A API call.
            Example:
                {'additionalInterfaces': None,
                'capabilities': {'extensions': None,
                'pushNotifications': None,
                'stateTransitionHistory': None,
                'streaming': False},
                'defaultInputModes': ['text'],
                'defaultOutputModes': ['text'],
                'description': (
                    'A helpful assistant agent that can answer questions.'
                ),
                'documentationUrl': None,
                'iconUrl': None,
                'name': 'Q&A Agent',
                'preferredTransport': 'JSONRPC',
                'protocolVersion': '0.3.0',
                'provider': None,
                'security': None,
                'securitySchemes': None,
                'signatures': None,
                'skills': [{
                    'description': (
                        'A helpful assistant agent that can answer questions.'
                    ),
                    'examples': ['Who is leading 2025 F1 Standings?',
                        'Where can i find an active volcano?'],
                    'id': 'question_answer',
                'inputModes': None,
                'name': 'Q&A Agent',
                'outputModes': None,
                'security': None,
                'tags': ['Question-Answer']}],
                'supportsAuthenticatedExtendedCard': True,
                'url': 'http://localhost:8080/',
                'version': '1.0.0'}
    Returns:
        A callable object that executes the method on the Agent Engine via
        the A2A API.
    rY   c           	        K   | j                   st        d      | j                  st        d      t        di t	        j
                        }|j                  r(|j                  t        j                  k7  rt        d      t        |d      st        j                  |_        |j                  r!|j                  j                  rt        d      t        |j                  d      sd|j                  _        | j                   j                  j                  j                  j                  d      }| j                   j                  j                  j                   }| d| d| j                  j"                   d	|_        t'        t        j                  gd
t)        j*                  dd| j                   j                  j,                  j.                   i            }t1        |      }|j3                  |      }dk(  r9|j5                  t7        di |      }g }	|2 3 d{   }
|	j9                  |
       dk(  r$|j;                  t=        di |       d{   }|S dk(  r$|j?                  tA        di |       d{   }|S dk(  r|jC                          d{   }|S t        d       7 6 |	S 7 a7 :7 w)z>Wraps an Agent Engine method, creating a callable for A2A API.r  r  zBOnly HTTP+JSON is supported for preferred transport on agent card preferred_transportziStreaming is not supported in Agent Engine, please change a2a_agent_card.capabilities.streaming to False.	streamingFr  z/a2aTAuthorizationzBearer )headers)supported_transportsuse_client_preferencehttpx_clienton_message_sendNon_get_taskon_cancel_taskhandle_authenticated_agent_cardzUnknown method name: rG   )"r  r   r  r!   r  r  r  r"   	http_jsonr   capabilitiesr  _api_client_http_optionsbase_urlrstripapi_versionr;   r  r&   httpxAsyncClient_credentialstokenr'   createsend_messager#   r)   get_taskr%   cancel_taskr$   get_card)rI   rJ   r@   r!  r#  r  factoryclientr  chunkschunkr   r   s              rK   r  z$_wrap_a2a_operation.<locals>._method  s    =>>  ?@@"<TZZ
%;< ..226G6Q6QQT 
 ~'<=1B1L1LN. &&>+F+F+P+PB 
 ~22K@49N''1 ??..<<EELLSQoo11??KK (z;-q9J9J9O9O8PPTU !++" #'**#!$//"="="J"J"P"P!QR
  '/++**7+<V+<=HF' % %ee$M)#___-Fv-FGGH  ,,#//0Fv0FGGH  ==#__..H  4[MBCC%xMGG.sZ   HKJ9!J7"J9%5KJ<(KJ>K"K #K7J99K>K K)r   )r   r   r  s   `` rK   rw  rw    s    \D DL NrM   r  c              #   
  K   | j                   sd y| j                   j                  d      D ]  }|s	 t        j                  |      }| ! y# t        $ r%}t
        j                  d| d|        Y d}~0d}~ww xY ww)a   Converts the body of the HTTP Response message to JSON format.

    Args:
        http_response (google.genai.types.HttpResponse):
            Required. The httpbody body to be converted to JSON object(s).

    Yields:
        Any: A JSON object or line of the original body or None.
    Nr  zfailed to parse json: rV  )bodyr  r  r  r   r   r   )r  r  r   s      rK   r
  r
  ;  s      
 ""((. Pzz$' J  P!7v]1#NOOPs.   2BAB	B A;6B;B  Bresource_limitsc                    t        | t              st        dt        |              d| vsd| vrt	        d      t        | d         }| d   }|dvrt        d|       t        |t              r|j                  d      st        d|       	 t        |d	d
       }|dkD  rt        d| d      |dkD  rd}n|dkD  rd}n|dkD  rd}n
|dkD  rd}nd}||k  rt        d| d| d|       y	# t        $ r t        d| d      w xY w)ay  Validates the resource limits.

    Checks that the resource limits are a dict with 'cpu' and 'memory' keys.
    Checks that the 'cpu' value is one of 1, 2, 4, 6, 8.
    Checks that the 'memory' value is a string ending with 'Gi'.
    Checks that the memory size is smaller than 32Gi.
    Checks that the memory size requires at least the specified number of CPUs.

    Args:
        resource_limits: The resource limits to be validated.

    Raises:
        TypeError: If the resource limits are not a dict.
        KeyError: If the resource limits do not contain 'cpu' and 'memory' keys.
        ValueError: If the 'cpu' value is not one of 1, 2, 4, 6, 8.
        ValueError: If the 'memory' value is not a string ending with 'Gi'.
        ValueError: If the memory size is too large.
        ValueError: If the memory size requires more CPUs than the specified
        'cpu' value.
    z$resource_limits must be a dict. Got cpumemoryz5resource_limits must contain 'cpu' and 'memory' keys.)r               z9resource_limits['cpu'] must be one of 1, 2, 4, 6, 8. Got GizAresource_limits['memory'] must be a string ending with 'Gi'. Got NzInvalid memory value: z&. Must be an integer followed by 'Gi'.    zMemory size of z) is too large. Must be smaller than 32Gi.   r:     r9  r8  r7  r   z requires at least z CPUs. Got )	r   rp   r  r
  KeyErrorintr   rq   rW  )r3  r5  
memory_str	memory_gbmin_cpus        rK   "_validate_resource_limits_or_raiserE  S  s   * ot,>tO?T>UVWWO#x'FNOO
oe$
%C *J
/!J3%P
 	
 j#&j.A.A$.G<!
 	



3B(	 2~j\)RS
 	
 2~	R	Q	Q
W}j\)<WI F5
 	
 -  
$ZL 1! !
 	

s   C. .Dc                 :    ddl m} t        | |j                        S )zChecks if the agent engine is an ADK agent.

    Args:
        agent_engine: The agent engine to check.

    Returns:
        True if the agent engine is an ADK agent, False otherwise.
    r   )adk) vertexai.agent_engines.templatesrG  r   r  )r4   rG  s     rK   _is_adk_agentrI    s     5lCJJ//rM   env_varsc                 |    d}|di}| |S t        | t              st        dt        |        d      || v r| S | |z  S )ac  Adds telemetry enablement env var to the env vars.

    This is in order to achieve default-on telemetry.
    If the telemetry enablement env var is already set, we do not override it.

    Args:
        env_vars: The env vars to add the telemetry enablement env var to.

    Returns:
        The env vars with the telemetry enablement env var added.
    *GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRYunspecifiedz!env_vars must be a dict, but got r!  )r   rp   r  r
  )rJ  rL  
env_to_adds      rK   _add_telemetry_enablement_envrO    s`      	5 / =mLJh%;DN;K1MNN1X=j  rM   )r=   r=   r   )rQ   rR   rd   r  r   r   r  r   r  r  loggingr   r   r   r  r   r   r  r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r$  r  google.api_corer   google.genaigoogle_genai_typesgoogle.protobufr   r   r=   r  version_infor   typing_extensionsbuiltin_module_namesr   rq   r|   r   packages_distributionsr   stdlib_module_namesr   	frozensetTYPE_CHECKINGrI  r   Bucketr   r
  rF  rN  
specifiersSpecifierSetr    	a2a.typesr!   r"   r#   r$   r%   
a2a.clientr&   r'   r   r   r$  r=  rA  rC  r   unionr  r  r%  r"  r<  !_DEFAULT_ASYNC_METHOD_RETURN_TYPEr@  (_DEFAULT_ASYNC_STREAM_METHOD_RETURN_TYPE_DEFAULT_GCS_DIR_NAMErm  r:  rq  "_DEFAULT_STREAM_METHOD_RETURN_TYPEr   r>  rB  r  0_FAILED_TO_REGISTER_API_METHODS_WARNING_TEMPLATEr  rl  r   r  r;  r?  rv  r   r   r   r   ro  rp  	getLoggerr   runtime_checkablerE   rU   rX   r^   ra   rg   rl   r  rt   ru   r}   rw   r   r   r   r   AgentEngineOperationAgentEngineMemoryOperation$AgentEngineGenerateMemoriesOperationr   r   r   r   floatr   r   r   r   rp   r   r   boolr  r   r'  r8  rr   rD  
ModuleTyperG  r.  rO  r   r   r   rc  r   r  r  r  r   r`  ra  rb  r  r  r  r  r  r  r  r   rr  rs  rt  ru  rw  HttpResponser
  rE  rI  rO  rG   rM   rK   <module>rp     sc   + 
   4  	   	 	 
       "   & 4 & ' " w +.+.+C+C8C=C=1113 GC#$67 7+.+B+B)C.B
 
$ 'NI.(($+NNS	2
 
((55M'#,#7#7#D#DtCyD
  7I)GL!ML%O ) ' % )*001EF## '	  + $4 !$8 !+? (& 
& "  . %4 "&z'BC , #6  ,  1 . #   '   % " &  ,/1=	  368D	#  
		8	9 = = = LX L L G8 G G 8h 8 8 G( G G , , , 8   
+#Hi#/(1(9%1  !Ye !]E)1 ]E@Y i 
,I ,
 "$$**446 8  S c SV J $&	 0 !	
 	@ $&	 + !	
 	@ 26	7#s(#7 x}gc8O3L.L&MMN7  .	7
 #7t2 2 S$s)^$2 
%--	2jGS#X'G	%--GW%6%6 4 . "&&( tSt #t #s(#	t
 smt 
#s(^tn%$c]%$ !%$ 38_	%$Z "&  	
 # *  
#tCy.,	e&6&6 		(8(8 		1A1A 		E,<,< 	5#3#3  # S(?++,J "&6
)*6
 8C=)6
 Xc]+	6

 6
 6
 6
 6
 #6
 
6
| 	^S))^S  S(C:xS'99::;^S 
^SH /3CG=A*T	*T Xc]+*T $GC#,>$?@	*T
  (S(9:*T S#X*TZemm S#X < (,	tCH~u}},	-emm$ ]]>9 9 9 	9
 
94
?3-
? 
? 	
?
 

?ASMA A 	A
 
A&;c]; 	;6 9=sm Dhsm!345 c]	$93-9 sm9 
	9x  	 s) 
#Y	B -1 8C=) c]	0{ { {|
C 
C 
HS#X<N 
# (382D D##c9S#s]++,#L! !#xPS}BT9U !H##c=%%&#LtS tc thsDQTI~>V tn&8&E&E (SV- 0D
S#X D
4 D
N0 5 0$ 0!tCsCx012!d3c3h'()!I;  .+-8C=-.  =:<GC#$67<=  7+4;)C.67 ( ($'S	'( ( '#&tCy&'* 	^$ IGLMLOB ( s~   %\ :\. ]	 ]$ "]< 7$^ =^0 \+*\+.]]	]! ]!$]98]9<^^^-,^-0	^=<^=