From 5b2a8df569e37e390992f04503c447cb49d19e00 Mon Sep 17 00:00:00 2001 From: Google Team Member Date: Fri, 6 Nov 2026 11:05:21 -0800 Subject: [PATCH] fix: surface backend error messages in Java and Go Interactions SDK errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since `openapi-generation` v2.960.7, Speakeasy fills the error message from `error.message` only for operations with a typed error schema (the Interactions `*ClientError` / `*ServerError` carriers in Java and Go). The untyped fallback (`GaosApiException` in Java, `APIError` in Go), used by operations without a typed error schema and by bodies that do not match it (e.g. the `[{error: {...}}]` arrays streaming endpoints return), still passes the placeholder `"API error occurred"` and leaves the backend's `{error: {message}}` only in the raw response body. So a 400 validation error from such an operation surfaces in Java as `"400 . API error occurred"` and in Go as `APIError.Message == "API error occurred"`, and no Java gaos error populates `ApiException.status()` or carries `error.details`, so even typed errors read `"400 . "`. - **Java**: Emits package-private `GaosErrorBody` (`scripts/templates/error_body.java.tmpl`). `GaosBaseException`, `GaosClientException`, and `GaosServerException` forward `GaosErrorBody.status(body)` (OnePlatform `error.status`, else the Interactions API string `error.code`, else `""`) and `GaosErrorBody.message(message, body)` to `com.google.genai.errors.ApiException`. The message is `error.message` plus any `error.details`, appended one per line after `\nDetails: `; for `{error: {...}}` bodies this matches the native `ApiException.getErrorMessageFromBody`, so gaos and native errors read the same. - **Go**: Emits `messageFromBody` (`scripts/templates/error_body.go.tmpl`) in `interactions/models/apierrors/errorbody.go` and calls it from `NewAPIError`, which fills `APIError.Message` from `error.message`. - Both read the `{error: {...}}` object and the single-element `[{error: {...}}]` array that streaming endpoints return, replace only the placeholder (a more specific message is kept), and keep the placeholder when the body is not a recognized JSON error (including multi-element arrays). - **Behavior change (Java)**: `getMessage()` now spans several lines for errors that carry `error.details` (e.g. `400 INVALID_ARGUMENT. Bad thing\nDetails: {"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"API_KEY_INVALID"}`), so callers that log or compare the text see the extra line. `message()` gains the same lines: on the per-operation `*ClientError` / `*ServerError` carriers it is the message text alone (`Bad thing\nDetails: …`), as on the native `ApiException`, while `GaosApiException` keeps Speakeasy's existing override that returns the full `getMessage()` string. Go's `APIError.Message` stays `error.message` only; details remain in the body that `Error()` appends, following each language's native convention. - **Documented differences from the native Java `ApiException`**: `status()` falls back to the Interactions `error.code` where native uses the HTTP reason phrase (empty on HTTP/2); a single-element array also yields its details and an empty missing status where native `throwFromErrorNode` drops details and reports `UNKNOWN`; a multi-element array keeps the placeholder where native reads the first element. These are stated in the `GaosErrorBody` Javadoc and pinned by tests. - **Sync hardening & tests**: `reparent_java_error` replacements in `sync_speakeasy_outputs.py` now use `_replace_once`, so generator template changes fail loudly at sync time; adds `patch_go_apierrors`; adds Java (including parity and divergence tests against the native `ApiException`), Go, and sync unit tests. PiperOrigin-RevId: 1015698193 --- .github/workflows/mypy.yml | 2 +- google/genai/_gaos/utils/annotations.py | 18 ++++++------ google/genai/_gaos/utils/logger.py | 7 ++++- google/genai/tests/client/conftest.py | 29 +++++++++++++++++++ .../genai/tests/client/test_async_stream.py | 6 ---- .../client/test_client_initialization.py | 8 ++--- .../genai/tests/client/test_custom_client.py | 2 +- .../genai/tests/client/test_httpx2_client.py | 3 ++ google/genai/tests/client/test_retries.py | 6 ---- 9 files changed, 51 insertions(+), 30 deletions(-) create mode 100644 google/genai/tests/client/conftest.py diff --git a/.github/workflows/mypy.yml b/.github/workflows/mypy.yml index 7cdb390dd8..92860fb20c 100644 --- a/.github/workflows/mypy.yml +++ b/.github/workflows/mypy.yml @@ -10,7 +10,7 @@ on: - main env: - SPEAKEASY_VERSION: v2.959.1 + SPEAKEASY_VERSION: v2.960.7 jobs: mypy: diff --git a/google/genai/_gaos/utils/annotations.py b/google/genai/_gaos/utils/annotations.py index a1f08f0002..e54156f01d 100644 --- a/google/genai/_gaos/utils/annotations.py +++ b/google/genai/_gaos/utils/annotations.py @@ -38,24 +38,24 @@ def get_discriminator(model: Any, fieldname: str, key: str) -> str: """ upper_fieldname = fieldname.upper() + def to_discriminator(value: Any) -> str: + """Convert a discriminator value to a string, using the value of enum members.""" + if isinstance(value, Enum): + return f"{value.value}" + return f"{value}" + def get_field_discriminator(field: Any) -> Optional[str]: """Search for the discriminator attribute in a given field.""" if isinstance(field, dict): if key in field: - return f"{field[key]}" + return to_discriminator(field[key]) if hasattr(field, fieldname): - attr = getattr(field, fieldname) - if isinstance(attr, Enum): - return f"{attr.value}" - return f"{attr}" + return to_discriminator(getattr(field, fieldname)) if hasattr(field, upper_fieldname): - attr = getattr(field, upper_fieldname) - if isinstance(attr, Enum): - return f"{attr.value}" - return f"{attr}" + return to_discriminator(getattr(field, upper_fieldname)) return None diff --git a/google/genai/_gaos/utils/logger.py b/google/genai/_gaos/utils/logger.py index 65f61771a0..dd339d4c4e 100644 --- a/google/genai/_gaos/utils/logger.py +++ b/google/genai/_gaos/utils/logger.py @@ -41,7 +41,12 @@ def get_body_content(req: httpx.Request) -> str: def get_default_logger() -> Logger: - if os.getenv("GOOGLE_GENAI_DEBUG"): + if os.getenv("GOOGLE_GENAI_DEBUG", "").strip().lower() in ( + "true", + "1", + "yes", + "on", + ): logging.basicConfig(level=logging.DEBUG) return logging.getLogger("google.genai") return NoOpLogger() diff --git a/google/genai/tests/client/conftest.py b/google/genai/tests/client/conftest.py new file mode 100644 index 0000000000..d02fa21cd6 --- /dev/null +++ b/google/genai/tests/client/conftest.py @@ -0,0 +1,29 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Shared fixtures for client tests.""" + +import pytest + +from ... import _api_client as api_client + + +@pytest.fixture(autouse=True) +def reset_has_aiohttp(): + # Some client tests override the module-level `has_aiohttp` flag; restore it + # so the override does not leak into later tests on the same pytest worker. + original = api_client.has_aiohttp + yield + api_client.has_aiohttp = original diff --git a/google/genai/tests/client/test_async_stream.py b/google/genai/tests/client/test_async_stream.py index 43b57eb033..95d92edfc3 100644 --- a/google/genai/tests/client/test_async_stream.py +++ b/google/genai/tests/client/test_async_stream.py @@ -101,12 +101,6 @@ def responses() -> api_client.HttpResponse: ) -@pytest.fixture(autouse=True) -def reset_has_aiohttp(): - yield - api_client.has_aiohttp = False - - def test_invalid_response_stream_type(responses: api_client.HttpResponse): """Tests that an invalid response stream type raises an error.""" api_client.has_aiohttp = False diff --git a/google/genai/tests/client/test_client_initialization.py b/google/genai/tests/client/test_client_initialization.py index 44937b82ac..99f1920d1f 100644 --- a/google/genai/tests/client/test_client_initialization.py +++ b/google/genai/tests/client/test_client_initialization.py @@ -60,12 +60,6 @@ ) -@pytest.fixture(autouse=True) -def reset_has_aiohttp(): - yield - api_client.has_aiohttp = False - - def test_ml_dev_from_gemini_env_only(monkeypatch): api_key = "gemini_api_key" monkeypatch.setenv("GEMINI_API_KEY", api_key) @@ -1199,6 +1193,8 @@ def test_client_ssl_context_explicit_initialization_async_args(): def test_client_initializes_httpx_clients_vertex_and_mldev(): """Verifies both Vertex and MLDev clients initialize non-null httpx clients with timeout=None.""" + # Keep the async path on httpx even when aiohttp is installed. + api_client.has_aiohttp = False mldev_client = Client(api_key="fake-api-key") assert mldev_client._api_client._httpx_client is not None assert mldev_client._api_client._async_httpx_client is not None diff --git a/google/genai/tests/client/test_custom_client.py b/google/genai/tests/client/test_custom_client.py index 73b9de453b..a6fb8712fb 100644 --- a/google/genai/tests/client/test_custom_client.py +++ b/google/genai/tests/client/test_custom_client.py @@ -72,7 +72,7 @@ def test_constructor_with_httpx_clients(): assert not vertexai_client.models._api_client._async_httpx_client.trust_env # Expect aiohttp to be disabled when httpx clients are provided, regardless of # whether aiohttp is installed. - assert not mldev_client.models._api_client._use_aiohttp() + assert not vertexai_client.models._api_client._use_aiohttp() # Aiohttp diff --git a/google/genai/tests/client/test_httpx2_client.py b/google/genai/tests/client/test_httpx2_client.py index aa220742db..5b9bfc8a02 100644 --- a/google/genai/tests/client/test_httpx2_client.py +++ b/google/genai/tests/client/test_httpx2_client.py @@ -591,6 +591,9 @@ async def test_aclose_when_async_httpx_client_is_none(monkeypatch): def test_vertexai_with_httpx2(monkeypatch): monkeypatch.setenv('GOOGLE_GENAI_HTTP_CLIENT', 'httpx2') + # Keep the async path on httpx2 even when aiohttp is installed. + target_api_client = getattr(api_client, 'public_api_client', api_client) + monkeypatch.setattr(target_api_client, 'has_aiohttp', False) client = Client( vertexai=True, project='fake-project', diff --git a/google/genai/tests/client/test_retries.py b/google/genai/tests/client/test_retries.py index a70244da67..2d09f24491 100644 --- a/google/genai/tests/client/test_retries.py +++ b/google/genai/tests/client/test_retries.py @@ -63,12 +63,6 @@ ) -@pytest.fixture(autouse=True) -def reset_has_aiohttp(): - yield - api_client.has_aiohttp = False - - def _final_codes(retried_codes: Sequence[int] = _RETRIED_CODES): return [code for code in range(100, 600) if code not in retried_codes]