Skip to content

feat(py/plugins/google-genai): raw Interactions HTTP client, converters, and options - #5855

Closed
cabljac wants to merge 8 commits into
jh-interactions-1-corefrom
jh-interactions-2-transport
Closed

cabljac wants to merge 8 commits into
jh-interactions-1-corefrom
jh-interactions-2-transport

Conversation

@cabljac

@cabljac cabljac commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Second slice of the #5806 split (stacked on #5854): minimal async HTTP client for the Google AI Interactions API, request/response converters between Genkit and Interactions wire types, ClientOptions resolution, shared error-mapping utilities, and the google-genai >=2.14.0,<3 bump.

Part of the stack splitting #5806; recombined it reproduces that PR byte-for-byte. Co-authored with @huangjeff5.

Breaking changes

  • google-genai dependency floor moves from >=1.63.0 to >=2.14.0,<3 (major version bump) for the Interactions SDK types. Downstream projects pinned below 2.x will fail to resolve.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces support for the Google AI Interactions API within the genkit-google-genai package, adding HTTP client helpers, message converters, configuration options, and utility functions, along with corresponding unit tests. It also bumps the google-genai dependency requirement to version 2.14.0. The review feedback highlights three key issues: a bug in ensure_tool_ids that can cause tool request and response ID mismatches when some requests already have a ref, a control flow anti-pattern in cancel_interaction where an exception is raised on a successful path, and a potential crash in status_from_api_error if error.code is non-numeric.

@cabljac
cabljac requested a review from hilariie August 3, 2026 09:38
cabljac and others added 3 commits August 4, 2026 09:52
…l refs

Core plumbing extracted from #5806: FinishReason.ABORTED (schema + typing),
cancel-operation action kind and registry lookup, background operation
lifecycle updates in _background.py, generate_operation/check_operation
plumbing in _ai, and a config_schema parameter on model_ref.

Co-authored-by: Jeff Huang <huangjeff@google.com>
genkit-schema.json is generated from this zod enum by export:schemas;
adding aborted only to the generated JSON left CI's clean-working-tree
check failing once the build regenerated the schema.

Co-authored-by: Jeff Huang <huangjeff@google.com>
…nishReason

Regenerates go/ai/gen.go from genkit-schema.json (FinishReasonAborted) and
narrows the runtime-parameterized ModelRequest cast to type[BaseModel] to
match _override_input_schema's signature.

Co-authored-by: Jeff Huang <huangjeff@google.com>
@cabljac
cabljac force-pushed the jh-interactions-2-transport branch from e079a08 to c5ac7b1 Compare August 4, 2026 08:52
cabljac and others added 4 commits August 4, 2026 10:43
mode='plain' replaced the field's core schema, so the config JSON schema
collapsed to an empty object, every traced dump warned, and mismatched
config instances passed validation. The field is now a left-to-right
union (dict | SerializeAsAny[ConfigT] | None) with a before-validator
coercing dicts into the bound schema; type checkers see ConfigT | None
with a shadow __init__ that accepts dicts. Validation also unnests the
wire output key so model_dump round-trips keep output config, which the
action input retry relies on when re-validating cross-schema configs.
Hardcoded googleai/vertexai suggestions misdirect users of other
plugins; build the hint from the registry's plugin names instead.
…rs, and options

Transport layer extracted from #5806: minimal async HTTP client for the
Google AI Interactions API, request/response converters between Genkit and
Interactions wire types, ClientOptions resolution, and shared error-mapping
utilities. Bumps google-genai to >=2.14.0,<3 for the Interactions SDK types.

Co-authored-by: Jeff Huang <huangjeff@google.com>
@cabljac
cabljac force-pushed the jh-interactions-2-transport branch from c5ac7b1 to 777692d Compare August 4, 2026 10:11
…e cases

Non-numeric APIError.code no longer crashes status mapping (the code
field comes straight from response JSON), malformed data URLs fail with
a descriptive error, and the multimodal embedding guard now names the
actual google-genai floor (2.14.0) instead of an uninstallable 2.3.0.
return f'{base_url}/{api_version}/{resource_path}'


def headers(*, api_key: str, client_options: ClientOptions | None) -> dict[str, str]:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The reserved-header strip is case-sensitive: custom.pop('x-goog-api-key') misses X-Goog-Api-Key, and unlike the JS Headers object a dict keeps both casings, so the wire request carries two api-key headers (verified via MockTransport). The existing strip test passes even with the pop lines deleted, because the explicit keys are spread after **custom and overwrite same-case duplicates anyway. Building through httpx.Headers (or lowercasing before the pops) fixes both, and the test should assert the reserved key is actually absent.

return step


def to_function_call_step(request: ToolRequest) -> FunctionCallStepParam:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Non-dict tool input is silently replaced with {}: ToolRequest(input='Paris') goes to the wire as arguments: {}, so on the next turn the model sees its own call with empty args. Scalar input schemas are legal in Genkit, and the JS equivalent throws here (zod parse) rather than dropping data. We should either box it like to_function_result_step does, or raise.

# Interactions creates (esp. Antigravity/Lyria) can run far longer than the
# shared client's 60s default, so this transport opts out of a wall clock.
CACHE_KEY = 'googleai-interactions'
NO_TIMEOUT = httpx.Timeout(None)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

httpx.Timeout(None) also disables the connect timeout, so with no ClientOptions.timeout set (the default), an unreachable host parks the coroutine forever with no DEADLINE_EXCEEDED. The comment only argues for dropping the wall clock; httpx.Timeout(None, connect=10.0) keeps that intent.

return self.model_copy(update=update) if update else self

@classmethod
def from_metadata(cls, metadata: dict[str, Any] | None) -> Self:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Two trust issues on the check/cancel path: from_metadata accepts whatever dict comes back on the operation, including a baseUrl, and google_ai_url never quotes the interaction id, so 'interactions/../../v1/models' resolves to a different endpoint once httpx normalizes it (verified). In a server flow the operation comes from the client, so a caller can point the plugin's authenticated request at an arbitrary host or path. Minimum fix: quote(interaction_id, safe='') and ignore or validate baseUrl from metadata.

@cabljac

cabljac commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Did a deeper adversarial pass over this slice and found a handful of real issues. The blocking ones are inline (api key persistence, header casing, scalar tool args). Lower priority, happy to fold into this PR or a follow-up: unrecognized interaction statuses leave done unset so polling never terminates, malformed custom parts escape as bare AttributeError, Retry-After: inf parses to infinity, annotations land in metadata as SDK objects rather than plain data, and custom/raw on ModelResponse share one dict.

return None


def client_options_for_operation(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Flagging a credential-handling concern with persisting resolved auth here, since the later slices pick this up. Raised with the core team separately, happy to take the fix once there's a direction.

return user_step


def to_interaction_steps(messages: list[Message]) -> list[StepParam]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocking: this history conversion is lossy. Mixed parts are reordered because inline content is buffered until the end, preserved unknownStep values are dropped on replay, and signed multimodal thoughts are reconstructed differently. Stateless Interactions history must replay model-generated steps exactly as received.

if isinstance(step, FunctionCallStep):
return [from_function_call_step(step)]
if isinstance(step, FunctionResultStep):
return [from_function_result_step(step)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

function_result is client input echoed by Interactions, similar to user_input. Keeping it here places the caller's ToolResponsePart inside a role="model" response and can duplicate that result when the history is sent again.

def to_function_result_step(response: ToolResponse) -> FunctionResultStepParam:
"""Compile a Genkit tool response into a function_result step."""
output = response.output
if isinstance(output, (str, dict, list)):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This treats every list as multimodal function-result content, but the wire only accepts lists of text/image content blocks. A normal tool result such as [1, 2] is therefore emitted as an invalid function_result. Could we validate content-block lists and box ordinary JSON arrays in an object, with tests for both cases?

CODE_EXECUTION_RESULT,
{
'output': result if isinstance(result, str) else json.dumps(result),
'outcome': 'OUTCOME_OK',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Failed tool results become successful as result failure state is lost during this conversion, even when is_error=True

@hilariie

hilariie commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Closing as superseded by #6240, which landed the Interactions HTTP client and converters.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants