|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# |
| 15 | + |
| 16 | +"""Live AgentEngine API client.""" |
| 17 | + |
| 18 | +import contextlib |
| 19 | +import json |
| 20 | +from typing import Any, AsyncIterator, Dict, Optional |
| 21 | +import google.auth |
| 22 | + |
| 23 | +from google.genai import _api_module |
| 24 | +from .types import QueryAgentEngineConfig, QueryAgentEngineConfigOrDict |
| 25 | + |
| 26 | + |
| 27 | +try: |
| 28 | + from websockets.asyncio.client import ClientConnection |
| 29 | + from websockets.asyncio.client import connect as ws_connect |
| 30 | +except ModuleNotFoundError: |
| 31 | + # This try/except is for TAP, mypy complains about it which is why we have the type: ignore |
| 32 | + from websockets.client import ClientConnection # type: ignore |
| 33 | + from websockets.client import connect as ws_connect # type: ignore |
| 34 | + |
| 35 | + |
| 36 | +class AsyncLiveAgentEngineSession: |
| 37 | + """AsyncLiveAgentEngineSession.""" |
| 38 | + |
| 39 | + def __init__(self, websocket: ClientConnection): |
| 40 | + self._ws = websocket |
| 41 | + |
| 42 | + async def send(self, query_input: Dict[str, Any]) -> None: |
| 43 | + """Send a query input to the Agent. |
| 44 | +
|
| 45 | + Args: |
| 46 | + query_input: A JSON serializable Python Dict to be send to the Agent. |
| 47 | + """ |
| 48 | + |
| 49 | + try: |
| 50 | + json_request = json.dumps({"bidi_stream_input": query_input}) |
| 51 | + except json.JSONEncoderError as exc: |
| 52 | + raise ValueError( |
| 53 | + "Failed to encode query input to JSON in live_agent_engines: " |
| 54 | + f"{str(query_input)}" |
| 55 | + ) from exc |
| 56 | + await self._ws.send(json_request) |
| 57 | + |
| 58 | + async def receive(self) -> Dict[str, Any]: |
| 59 | + """Receive one response from the Agent. |
| 60 | +
|
| 61 | + Returns: |
| 62 | + A response from the Agent. |
| 63 | +
|
| 64 | + Raises: |
| 65 | + websockets.exceptions.ConnectionClosed: If the connection is closed. |
| 66 | + """ |
| 67 | + |
| 68 | + response = await self._ws.recv() |
| 69 | + try: |
| 70 | + return json.loads(response) |
| 71 | + except json.decoder.JSONDecodeError as exc: |
| 72 | + raise ValueError( |
| 73 | + "Failed to parse response to JSON in live_agent_engines: " |
| 74 | + f"{str(response)}" |
| 75 | + ) from exc |
| 76 | + |
| 77 | + async def close(self) -> None: |
| 78 | + """Close the connection.""" |
| 79 | + await self._ws.close() |
| 80 | + |
| 81 | + |
| 82 | +class AsyncLiveAgentEngines(_api_module.BaseModule): |
| 83 | + """AsyncLiveAgentEngines. |
| 84 | +
|
| 85 | + Example usage: |
| 86 | +
|
| 87 | + .. code-block:: python |
| 88 | +
|
| 89 | + from pathlib import Path |
| 90 | +
|
| 91 | + from google import genai |
| 92 | + from google.genai import types |
| 93 | +
|
| 94 | + class MyAgentEngine(client): |
| 95 | + def bidi_stream_query(self, input_queue: asyncio.Queue): |
| 96 | + while True: |
| 97 | + input = await input_queue.get() |
| 98 | + yield {"output": f"Agent received {input}!"} |
| 99 | +
|
| 100 | + client = vertexai.Client(project="my-project", location="us-central1") |
| 101 | + agent_engine = client.agent_engines.create(agent) |
| 102 | +
|
| 103 | + async with client.aio.live.agent_engines.connect( |
| 104 | + agent_engine=agent_engine.api_resource.name, |
| 105 | + setup={"class_method": "bidi_stream_query"}, |
| 106 | + ) as session: |
| 107 | + await session.send(input={"input": "Hello world"}) |
| 108 | +
|
| 109 | + response = await session.receive() |
| 110 | + # {"output": "Agent received Hello world!"} |
| 111 | + ... |
| 112 | + """ |
| 113 | + |
| 114 | + @contextlib.asynccontextmanager |
| 115 | + async def connect( |
| 116 | + self, |
| 117 | + *, |
| 118 | + agent_engine: str, |
| 119 | + config: Optional[QueryAgentEngineConfigOrDict] = None, |
| 120 | + ) -> AsyncIterator[AsyncLiveAgentEngineSession]: |
| 121 | + """Connect to the agent deployed to Agent Engine in a live (bidirectional streaming) session. |
| 122 | +
|
| 123 | + Args: |
| 124 | + agent_engine: The resource name of the Agent Engine to use for the |
| 125 | + live session. |
| 126 | + config: The optional configuration for starting the live Agent Engine |
| 127 | + session. Custom class_method and an optional initial input could be |
| 128 | + provided. If no class_method is provided, the default class_method |
| 129 | + "bidi_stream_query" will be used by the Agent Engine. |
| 130 | +
|
| 131 | + Yields: |
| 132 | + An AsyncLiveAgentEngineSession object. |
| 133 | + """ |
| 134 | + if isinstance(config, dict): |
| 135 | + config = QueryAgentEngineConfig(**config) |
| 136 | + |
| 137 | + agent_engine_resource_name = agent_engine |
| 138 | + if not agent_engine_resource_name.startswith("projects/"): |
| 139 | + agent_engine_resource_name = f"projects/{self._api_client.project}/locations/{self._api_client.location}/reasoningEngines/{agent_engine}" |
| 140 | + request_dict = {"setup": {"name": agent_engine_resource_name}} |
| 141 | + if config.class_method: |
| 142 | + request_dict["setup"]["class_method"] = config.class_method |
| 143 | + if config.input: |
| 144 | + request_dict["setup"]["input"] = config.input |
| 145 | + |
| 146 | + request = json.dumps(request_dict) |
| 147 | + |
| 148 | + if not self._api_client._credentials: |
| 149 | + # Get bearer token through Application Default Credentials. |
| 150 | + creds, _ = google.auth.default( # type: ignore |
| 151 | + scopes=["https://www.googleapis.com/auth/cloud-platform"] |
| 152 | + ) |
| 153 | + else: |
| 154 | + creds = self._api_client._credentials |
| 155 | + # creds.valid is False, and creds.token is None |
| 156 | + # Need to refresh credentials to populate those |
| 157 | + if not (creds.token and creds.valid): |
| 158 | + auth_req = google.auth.transport.requests.Request() # type: ignore |
| 159 | + creds.refresh(auth_req) |
| 160 | + bearer_token = creds.token |
| 161 | + |
| 162 | + original_headers = self._api_client._http_options.headers |
| 163 | + headers = original_headers.copy() if original_headers is not None else {} |
| 164 | + headers["Authorization"] = f"Bearer {bearer_token}" |
| 165 | + |
| 166 | + base_url = self._api_client._websocket_base_url() |
| 167 | + if isinstance(base_url, bytes): |
| 168 | + base_url = base_url.decode("utf-8") |
| 169 | + uri = ( |
| 170 | + f"{base_url}/ws/google.cloud.aiplatform." |
| 171 | + f"{self._api_client._http_options.api_version}" |
| 172 | + ".ReasoningEngineExecutionService/BidiQueryReasoningEngine" |
| 173 | + ) |
| 174 | + |
| 175 | + async with ws_connect( |
| 176 | + uri, additional_headers=headers, **self._api_client._websocket_ssl_ctx |
| 177 | + ) as ws: |
| 178 | + await ws.send(request) |
| 179 | + yield AsyncLiveAgentEngineSession(websocket=ws) |
0 commit comments