Skip to content

fix(google-genai)!: Interactions API fixes for Antigravity, Lyria and DR - #78

Open
ifielker wants to merge 2 commits into
mainfrom
if-pyInteractionFixes
Open

ifielker wants to merge 2 commits into
mainfrom
if-pyInteractionFixes

Conversation

@ifielker

Copy link
Copy Markdown
Contributor

fix(google-genai)!: Interactions API fixes for Antigravity, Lyria and Deep Research

Fixes in the code shared by the Interactions API models (Antigravity, Lyria
and Deep Research), ported from the JS plugin. This also prepares that code
for Gemini models, which move to the Interactions API in a follow-up PR.
Gemini, Gemma, Imagen, Veo and embedder models are unchanged.

Usage

  • Per-modality token counts: the token counts per modality were put into
    Genkit's input_characters, input_images, output_audio_files, ...
    fields, which count characters and media parts (that's what
    generateContent models report). They're now in usage.custom as
    inputTextTokens, inputImageTokens, outputAudioTokens, ..., along with
    toolUseTokens and per-tool counts such as googleSearchCount.
  • Character and media-part counts: Antigravity and Lyria now count
    input_characters, input_images, ... from the request and response
    messages, the same way generateContent models do
    (GenerationUsage.from_messages), so telemetry that reads them gets real
    counts. Deep Research is a background model: its check and cancel calls
    don't have the request, so it doesn't get these counts.

Errors and blocked responses

  • Interactions error codes: the API reports errors with its own string
    codes (service_unavailable, quota_exceeded, model_not_found,
    malformed_function_call, ...). They're now mapped to Genkit statuses
    (same table as the JS plugin), both in error responses and in failed
    interactions. Before, these failures were UNKNOWN or got the HTTP
    code's status, so Retry and Fallback couldn't act on them (e.g. a quota
    error wasn't RESOURCE_EXHAUSTED). malformed_function_call,
    unexpected_tool_call and no_image are ABORTED, which Retry retries
    (the server's message says to retry).
  • Content-policy blocks: an interaction that failed with a
    content-policy code (safety, recitation, blocklist, spii, ...) now
    returns a response with finish_reason='blocked', the server's message
    and no content, like a blocked generateContent response. It used to
    raise. A Deep Research operation ends with that response as its output
    instead of an error.
  • Error body in a list: the Interactions API sometimes sends its error
    body wrapped in a one-element JSON array (e.g. for a bad API key). The
    error message was the raw JSON text; the body is now unwrapped first.

Documents and media

  • Documents of any type: only application/pdf was sent as a document;
    any other non image/audio/video type (CSV, Word, Excel, text, ...) raised
    Unsupported media type before the request. They're now all sent as
    document, and the server decides which types it accepts (it accepts
    more than the PDF and CSV in its published spec).
  • Media without a content type: the type is now read from a data: URL
    or guessed from a few file extensions (jpg, jpeg, png, mp4, pdf, as in
    JS). A URL whose type still isn't known (e.g. a Files API URI) is sent
    without a mime_type, as video for YouTube links and document
    otherwise, and the server works out the type. It used to raise. A data:
    URL with no type still raises.
  • Video processing mode: a video part's metadata['processing']
    ('static' or 'agentic') is now sent on the video block.
  • Audio returned without a content type: the server sends some audio
    (e.g. single-voice speech) as raw 16-bit PCM with sample_rate and
    channels but no mime_type, which gave a media part with an empty URL.
    It's now labelled audio/l16; rate=<sample_rate>; channels=<channels>
    (24000 and 1 when missing), so it can be played. A mime_type from the
    server always wins.

Code execution history

Code execution steps sent back in the history:

  • Missing call IDs: history saved from generateContent has no call ID
    on its code execution parts, and the API rejects an empty id /
    call_id. A call without an ID now gets one, and the next result without
    an ID gets the same one (a result with no call waiting gets its own ID).
    Existing IDs are kept.
  • Language: it was always sent as python. It's now the saved language,
    lower-cased (default python): PYTHON from generateContent is
    accepted, and bash steps (Antigravity runs bash) are sent back as
    bash.

New option: experimental_debug_traces

GoogleAI(experimental_debug_traces=True) adds an httpRequest trace span
to each Interactions API create and get call, with the endpoint, the request
body, the headers (API key replaced by <REDACTED> (N characters)) and the
response body. It's the JS plugin's experimental_debugTraces: a plugin
option only (not per request), and cancel calls aren't traced. Experimental:
the span contents may change.

Breaking changes

  • Usage fields: for Antigravity, Lyria and Deep Research,
    usage.input_characters, input_images, input_audio_files,
    input_videos and the output_* fields no longer hold token counts. Read
    the matching usage.custom.*Tokens field instead.
  • Blocked responses don't raise: a content-policy failure returns a
    response with finish_reason='blocked' instead of raising a
    GenkitError; for Deep Research it's the operation's output.
  • Error statuses: errors with an Interactions error code get that code's
    status instead of UNKNOWN or the HTTP status (e.g. NOT_FOUND for
    model_not_found on a 400), so Retry may now retry some failures it
    didn't before (ABORTED, UNAVAILABLE, RESOURCE_EXHAUSTED).

Testing

  • Unit tests (ported from the JS plugin's tests, with the same data): usage
    mapping and character counts; every Interactions error code;
    content-policy codes returning blocked, with usage; error bodies in a
    list; Interactions codes winning over the HTTP status; CSV, Word, Excel
    and text documents; URLs without a content type (YouTube, Files API);
    video processing; audio without a mime_type; code execution history
    without IDs and with bash; the httpRequest span (create and get traced
    with the exact input and output, nothing by default, cancel not traced,
    errors still raised, can't be turned on per request).
  • Live (Gemini API):
    • An Antigravity call that ran code: its code execution steps came back
      with language: bash (kept as bash when the history is sent back);
      usage had real character counts, with the token counts in
      usage.custom; the httpRequest span had the request and response,
      with the API key hidden.
    • An Antigravity call with a small CSV sent inline: the server accepted it
      as a document and answered from it correctly.
    • A Lyria 3 clip: one audio/mpeg part; usage counted one output audio
      file, with the input token count in usage.custom.
  • Content-policy blocks, error codes, error bodies in a list and code
    execution history from generateContent are hard to trigger on purpose,
    so they weren't checked live with this plugin; the same behaviour was
    checked live in the JS and Dart plugins.
  • ruff check, pyright and the package's unit tests (1556) pass.

@ifielker ifielker changed the title fix(google-genai): Interactions API fixes for Antigravity, Lyria and DR fix(google-genai)!: Interactions API fixes for Antigravity, Lyria and DR Nov 11, 2026
@ifielker
ifielker force-pushed the if-pyInteractionFixes branch from 8ba4687 to 30d70a9 Compare November 11, 2026 18:54
@ifielker
ifielker requested a review from huangjeff5 November 11, 2026 19:47
@ifielker
ifielker added this pull request to stack #106 November 11, 2026 20:13
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.

if (blocked := blocked_response(interaction)) is not None:
op.output = blocked
else:
op.error = Failure(message=interaction_error_message(interaction) or FAILED_MESSAGE)

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.

A failed Deep Research job with quota_exceeded or malformed_function_call ends with op.error = Failure(message=...) and no status, while the same interaction on generate raises RESOURCE_EXHAUSTED / ABORTED from the new table. Someone polling check_operation can't tell a quota failure from a bad request.

I suggest setting status=interaction_error_status(code) on the Failure here.

# `language` as 'python' only; our own Interactions types remove it.
language = cast(
Literal['python'],
(stored_language.lower() if isinstance(stored_language, str) else '') or CODE_LANGUAGE,

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.

Two shapes of saved code-execution history get a 400 when resent (checked live). LANGUAGE_UNSPECIFIED becomes language_unspecified after .lower() ("Supported values: 'python', 'bash'"), and a block that printed nothing has output=None, so we send result: null ("must be a string, or Content[]").

I suggest only passing through python / bash (else python), and sending '' when output is missing.


def first_error(interaction: Interaction) -> tuple[object, str | None]:
"""The code and message of the interaction's first top-level error, if any."""
for err in interaction.errors or []:

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.

On google-genai 2.14 to 2.16, which pyproject.toml still allows (>=2.14.0), Interaction has no errors field, so the errors come back as plain dicts and err.code raises AttributeError on any failed or blocked turn. uv run --with google-genai==2.14.0 pytest tests/interactions gives 41 failures. processing on video blocks also only exists from 2.18.

I suggest bumping the floor to google-genai>=2.18.0.

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.

``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.

@huangjeff5

Copy link
Copy Markdown
Collaborator

Heads up — #78 conflicts with a couple of my PRs that landed on main after you branched, sorry about that. Should be quick:

  • _interactions/_client.py error path — feat(py): keyless GoogleAI init, context.secrets on embedders, and ErrorReason.INVALID_CREDENTIALS #49 landed after you branched and added ErrorReason.INVALID_CREDENTIALS plus a rejected_credentials check right here: a bad key or token comes back as UNAUTHENTICATED with that reason. We went that way for DX: Gemini reports a bad key as the same INVALID_ARGUMENT it uses for a malformed request, so without the reason an app has to parse "API key not valid" out of the message to tell "ask the user to fix their key" from "developer bug". With it, it's one check that works the same on every model: res.error.reason == ErrorReason.INVALID_CREDENTIALS. wdyt about running the rejected_credentials check first and falling back to your table?

    error_detail = unwrap_error_body(response.json())
    api_message, api_code = api_error_fields(error_detail)
    ...
    invalid_credentials = rejected_credentials(response.status_code, error_detail)
    error = provider_error(
        cause,
        http_status=response.status_code,
        status='UNAUTHENTICATED' if invalid_credentials else code_status,
        headers=response.headers,
        message=message,
        reason=ErrorReason.INVALID_CREDENTIALS if invalid_credentials else None,
    )

    rejected_credentials needs to run on the unwrapped error_detail here: the endpoint wraps the bad-key error in a list ([{"error": {..., "details": [{... "reason": "API_KEY_INVALID"}]}}]), and it reads the details from the unwrapped dict.

  • GoogleAI docstring in _google.py — feat(py): keyless GoogleAI init, context.secrets on embedders, and ErrorReason.INVALID_CREDENTIALS #49 made init keyless (a missing key warns instead of raising), so the Raises: ValueError block can go. Keep your experimental_debug_traces paragraph.

Thanks for the cleanup here, the error statuses especially were a real gap.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants