Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,7 @@ def __init__(
max_retries: int | None = None,
http_client_factory: Callable[[], httpx.AsyncClient] | None = None,
legacy_response_schema: bool = False,
experimental_debug_traces: bool = False,
) -> None:
"""Initializes the GoogleAI plugin.

Expand Down Expand Up @@ -666,6 +667,12 @@ def __init__(
``responseSchema`` field instead of ``responseJsonSchema``,
converted to its format; a schema that cannot be converted
raises ``INVALID_ARGUMENT``. Defaults to False.
experimental_debug_traces: Enables additional debug traces (e.g.

Copy link
Copy Markdown
Collaborator

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) with gemini-2.5-flash gives no span and no warning.

Maybe we can open with "Interactions API models only" until Gemini moves onto Interactions.

raw model API call details). Each Interactions API call
(Deep Research, Antigravity, Lyria) gets an ``httpRequest``
trace span with the endpoint, the request body, the headers
(API key hidden) and the response body. Experimental; the
span contents may change. Defaults to False.

Raises:
ValueError: If `api_key` is not provided and the 'GEMINI_API_KEY'
Expand Down Expand Up @@ -698,6 +705,7 @@ def __init__(
self._http_client_factory = _loop_local_http_client(http_client_factory)
self._base_url_pinned = bool(self._client_kwargs['http_options'].base_url)
self._legacy_response_schema = legacy_response_schema
self._experimental_debug_traces = experimental_debug_traces
self._list_actions_cache: list[Action | BackgroundAction[Any, Any]] | None = None

@loop_local_client
Expand Down Expand Up @@ -728,6 +736,7 @@ def _interactions_client_options(self) -> ClientOptions:
# The getter, not a client: Interactions calls it per request so
# each event loop gets its own client.
http_client_factory=self._http_client_factory,
experimental_debug_traces=self._experimental_debug_traces,
)

def _plugin_api_key(self) -> str | None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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':
Expand All @@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With experimental_debug_traces=True the span only redacts x-goog-api-key and authorization. A cookie, proxy-authorization or custom key header from GoogleAI(headers=...) goes into the trace as is, and so do auth headers inside the request body (DeepResearchConfig.mcp_servers[*].headers, Antigravity tool headers). Those spans land in the Dev UI and in any exporter that captures action input/output.

I suggest redacting every header except a small allowlist (content-type, user-agent, api-revision) by default, and redacting headers inside mcp_servers / tools in the traced body.

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,
Expand All @@ -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:
Expand All @@ -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)

@huangjeff5 huangjeff5 Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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 {"error": {"code": "prohibited_content", ...}}, which comes back here as finish_reason='failed' with FAILED_PRECONDITION, so blocked_response() never sees it.

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
Loading
Loading