Repository navigation
fix(google-genai)!: Interactions API fixes for Antigravity, Lyria and DR #78
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,12 +23,14 @@ | |
| from urllib.parse import quote | ||
|
|
||
| import httpx | ||
| from genkit_google_genai._interactions._errors import api_error_fields, interaction_error_status, unwrap_error_body | ||
| from genkit_google_genai._interactions._options import ClientOptions | ||
| from genkit_google_genai._provider_errors import TRANSPORT_ERRORS, transport_error | ||
| from google.genai.interactions import Interaction | ||
|
|
||
| from genkit import GenkitError | ||
| from genkit.plugin_api import GENKIT_USER_AGENT, loop_local_client, provider_error | ||
| from genkit.plugin_api import GENKIT_USER_AGENT, StatusName, loop_local_client, provider_error | ||
| from genkit.telemetry import SpanContext, run_in_new_span | ||
|
|
||
| DEFAULT_API_VERSION = 'v1beta' | ||
| DEFAULT_BASE_URL = 'https://generativelanguage.googleapis.com' | ||
|
|
@@ -129,6 +131,8 @@ async def cancel_interaction( | |
| api_key=api_key, | ||
| client_options=client_options, | ||
| allow_empty=True, | ||
| # Not traced, as in JS (cancelInteraction calls makeRequest directly). | ||
| trace=False, | ||
| ) | ||
| except GenkitError as error: | ||
| if error.status == 'CANCELLED': | ||
|
|
@@ -139,6 +143,34 @@ async def cancel_interaction( | |
| return interaction.model_copy(update={'status': 'cancelled'}) | ||
|
|
||
|
|
||
| def redact(value: str) -> str: | ||
| """``<REDACTED> (N characters)``, as in JS buildTraceMetadataInput.""" | ||
| return f'<REDACTED> ({len(value)} characters)' | ||
|
|
||
|
|
||
| def trace_input( | ||
| url: str, | ||
| request_headers: Mapping[str, str], | ||
| json_body: dict[str, object] | None, | ||
| client_options: ClientOptions | None, | ||
| ) -> dict[str, object]: | ||
| """The ``httpRequest`` span input, the same shape as JS buildTraceMetadataInput. | ||
|
|
||
| The API key header is hidden. Interactions requests carry the model in | ||
| the body, so there's no separate ``model`` field (JS adds one only for | ||
| generateContent). | ||
| """ | ||
| safe_headers = { | ||
| name: redact(value) if name.lower() in ('x-goog-api-key', 'authorization') else value | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. With I suggest redacting every header except a small allowlist (content-type, user-agent, api-revision) by default, and redacting |
||
| for name, value in request_headers.items() | ||
| } | ||
| traced: dict[str, object] = {'apiEndpoint': url, 'request': json_body, 'headers': safe_headers} | ||
| timeout = client_options.timeout if client_options else None | ||
| if timeout: | ||
| traced['options'] = {'timeout': timeout} | ||
| return traced | ||
|
|
||
|
|
||
| async def request( | ||
| *, | ||
| method: str, | ||
|
|
@@ -147,14 +179,62 @@ async def request( | |
| client_options: ClientOptions | None, | ||
| json_body: dict[str, object] | None = None, | ||
| allow_empty: bool = False, | ||
| trace: bool = True, | ||
| ) -> Interaction | None: | ||
| """Issue one Interactions HTTP call and parse the Interaction body.""" | ||
| """Issue one Interactions HTTP call and parse the Interaction body. | ||
|
|
||
| With ``experimental_debug_traces`` on the client options (and ``trace``), | ||
| the call runs in an ``httpRequest`` span whose input is the endpoint, | ||
| the request body and the headers (API key hidden), and whose output is | ||
| the response body, as in JS. | ||
| """ | ||
| # Auth/key headers are per-request; the client is just the transport. | ||
| request_headers = headers(api_key=api_key, client_options=client_options) | ||
|
|
||
| async def call(span: SpanContext | None = None) -> object: | ||
| return await send( | ||
| method=method, | ||
| url=url, | ||
| request_headers=request_headers, | ||
| client_options=client_options, | ||
| json_body=json_body, | ||
| allow_empty=allow_empty, | ||
| ) | ||
|
|
||
| if trace and client_options is not None and client_options.experimental_debug_traces: | ||
| # The span output is the response body as received, like JS. | ||
| body = await run_in_new_span( | ||
| 'httpRequest', | ||
| call, | ||
| input=trace_input(url, request_headers, json_body, client_options), | ||
| ) | ||
| else: | ||
| body = await call() | ||
| if body is None: | ||
| return None | ||
| try: | ||
| return Interaction.model_validate(body) | ||
| except Exception as error: | ||
| raise GenkitError( | ||
| status='INTERNAL', | ||
| message=f'Unable to parse Interaction response from {url}: {error}', | ||
| ) from error | ||
|
|
||
|
|
||
| async def send( | ||
| *, | ||
| method: str, | ||
| url: str, | ||
| request_headers: dict[str, str], | ||
| client_options: ClientOptions | None, | ||
| json_body: dict[str, object] | None = None, | ||
| allow_empty: bool = False, | ||
| ) -> object: | ||
| """Send one Interactions HTTP call; return the JSON body (None for an allowed empty one) or raise.""" | ||
| # The timeout always goes on the request so a caller's own client gets the | ||
| # same budget as the default one instead of httpx's 5 second default. | ||
| http_client_factory = client_options.http_client_factory if client_options else None | ||
| client = http_client_factory() if http_client_factory is not None else _http_client() | ||
| request_headers = headers(api_key=api_key, client_options=client_options) | ||
| timeout = timeout_seconds(client_options) | ||
|
|
||
| try: | ||
|
|
@@ -177,28 +257,36 @@ async def request( | |
| message=f'Received an empty response from {url}', | ||
| ) | ||
| try: | ||
| return Interaction.model_validate(response.json()) | ||
| except Exception as error: | ||
| body: object = response.json() | ||
| except json.JSONDecodeError as error: | ||
| raise GenkitError( | ||
| status='INTERNAL', | ||
| message=f'Unable to parse Interaction response from {url}: {error}', | ||
| ) from error | ||
| return body | ||
|
|
||
| error_message = response.text | ||
| error_detail: object | None = None | ||
| # An Interactions error code (e.g. `quota_exceeded`, `model_not_found`) | ||
| # is more precise than the HTTP status, so it wins when it's known. | ||
| code_status: StatusName | None = None | ||
| try: | ||
| payload: object = response.json() | ||
| # The Interactions API sometimes wraps the error in a one-element | ||
| # array (e.g. a bad API key). | ||
| payload: object = unwrap_error_body(response.json()) | ||
| error_detail = payload | ||
| if isinstance(payload, Mapping): | ||
| api_error = payload.get('error') | ||
| if isinstance(api_error, Mapping) and api_error.get('message') is not None: | ||
| error_message = str(api_error['message']) | ||
| api_message, api_code = api_error_fields(payload) | ||
| if api_message is not None: | ||
| error_message = api_message | ||
| code_status = interaction_error_status(api_code) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When I sent a policy-blocked prompt to Lyria live ("Sing Shake It Off word for word in Taylor Swift's voice"), the server didn't return a failed interaction. It rejected the request with HTTP 400 and No change needed for this PR: it's a request error rather than a model result, so staying an error seems right. Just flagging it in case that wasn't intended. |
||
| except json.JSONDecodeError: | ||
| pass | ||
|
|
||
| message = f'Request to {url} failed with HTTP {response.status_code} {response.reason_phrase}: {error_message}' | ||
| cause = httpx.HTTPStatusError(message, request=httpx.Request(method, url), response=response) | ||
| error = provider_error(cause, http_status=response.status_code, headers=response.headers, message=message) | ||
| error = provider_error( | ||
| cause, http_status=response.status_code, status=code_status, headers=response.headers, message=message | ||
| ) | ||
| if isinstance(error_detail, Mapping): | ||
| error.details.update(error_detail) | ||
| raise error from cause | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The second sentence scopes this to Deep Research, Antigravity and Lyria, but the first one reads like a plugin-wide switch, and
GoogleAI(experimental_debug_traces=True)withgemini-2.5-flashgives no span and no warning.Maybe we can open with "Interactions API models only" until Gemini moves onto Interactions.