Skip to content

feat(py/google-genai)!: GoogleAI and VertexAI take headers, timeout, max_retries and http_client_factory - #6826

Merged
huangjeff5 merged 2 commits into
mainfrom
feat/py-google-genai-network-kwargs
Nov 3, 2026
Merged

huangjeff5 merged 2 commits into
mainfrom
feat/py-google-genai-network-kwargs

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

GoogleAI and VertexAI take their network settings as plain keyword arguments: headers=, timeout= (seconds), max_retries= and http_client_factory= (a function returning an httpx.AsyncClient), next to base_url= and api_version=. Every SDK and Interactions model call goes through a client from http_client_factory, one per event loop. The http_options= and debug_config= arguments, which took google-genai SDK types, are removed.

import httpx
from genkit import Genkit
from genkit_google_genai import GoogleAI

# 1. Configure GoogleAI with custom headers, a 30 second timeout, 2 retries, and a proxy client
ai = Genkit(
    plugins=[
        GoogleAI(
            headers={'X-Team': 'search'},
            timeout=30,  # seconds
            max_retries=2,  # after the first attempt
            http_client_factory=lambda: httpx.AsyncClient(proxy='http://proxy.internal:3128'),
        )
    ]
)

# 2. Every model call goes through a client from http_client_factory, with your headers and timeout
response = await ai.generate(
    model=GoogleAI.gemini('gemini-2.5-flash'),
    prompt='Suggest a dish.',
)
print(response.text)
# => Smoked Salmon Tartine

# 3. Passing a client instead of a function fails at plugin setup
GoogleAI(http_client_factory=httpx.AsyncClient())
# => TypeError: http_client_factory takes a function that returns an httpx.AsyncClient, got AsyncClient.
#    Pass http_client_factory=lambda: httpx.AsyncClient(...). Genkit builds one client per event loop
#    because an AsyncClient only works on the loop that first used it.

# 4. Removed SDK-typed arguments raise TypeError at construction
GoogleAI(http_options={'timeout': 30000})
# => TypeError: GoogleAI.__init__() got an unexpected keyword argument 'http_options'

Changes

  • http_client_factory: Callable[[], httpx.AsyncClient] | None = None on GoogleAI and VertexAI: Genkit calls the function once per event loop and reuses that client for every call on the loop. Gemini, Veo, Virtual Try-On, embedders and Interactions models (Deep Research, Antigravity, Lyria) all send through it, including calls that override base_url, api_version or location. Genkit never closes these clients. OAuth token refresh (google-auth uses its own requests transport), Vertex evaluators and downloads of media URLs in prompts don't use it. Media URLs point at third-party hosts that a proxy or mTLS setup for Google would block.
  • timeout: float | None = None on GoogleAI and VertexAI, in seconds: Every request carries this timeout explicitly, so a timeout configured on the client from http_client_factory is not used. A model config's timeout (GeminiConfig, AntigravityConfig, DeepResearchConfig, LyriaConfig) overrides it for a single call. Without timeout, Gemini calls have no timeout and Interactions calls keep a 10 second connect limit. It must be finite and greater than 0, and converts to whole milliseconds rounding up, so 0.0001 sends 1 ms.
  • max_retries: int | None = None on GoogleAI and VertexAI: Retries a failed request this many times after the first attempt, using google-genai's backoff (about 1, 2, 4 seconds, doubling up to 60, with jitter) on HTTP 408, 429, 500, 502, 503, 504 and on connection errors and timeouts. Maps to HttpRetryOptions(attempts=max_retries + 1). Covers Gemini, Veo including operation polling, Virtual Try-On, embedders and model listing. Interactions models (Deep Research, Antigravity, Lyria) don't retry yet (#6964). Defaults to no retries, which is google-genai's default too.
  • headers: Mapping[str, str] | None = None on GoogleAI and VertexAI: Sends extra HTTP headers on every request. On Gemini, Veo, Virtual Try-On and embedders, Genkit appends its attribution tag to x-goog-api-client and user-agent case-insensitively, so {'User-Agent': 'acme'} goes out as one header instead of two. Interactions models (Deep Research, Antigravity, Lyria) replace a caller's x-goog-api-client with Genkit's.
  • Removed http_options and debug_config from GoogleAI and VertexAI: The constructors no longer expose google-genai's HttpOptions and DebugConfig classes.

Decisions

  • timeout is in seconds, matching Python convention: We checked what Python developers expect from an argument named timeout, and the answer is float seconds. The standard library (asyncio.wait_for, asyncio.timeout, socket.settimeout, subprocess.run, urllib.request.urlopen, threading.Event.wait), requests, httpx, aiohttp.ClientTimeout, the OpenAI and Anthropic SDKs, grpc-python and Genkit's own Ollama plugin all use it. google-genai's HttpOptions.timeout is milliseconds because it follows the proto/JS convention, which makes it the outlier in Python. There's no _seconds suffix because in Python the name already means seconds, and http_options= raises TypeError, so everyone migrating has to rewrite the call anyway. The migration note and docstrings call out the ms-to-seconds conversion. Per-request timeout on GeminiConfig and the Antigravity, Deep Research and Lyria configs is also in seconds (fix(py/google-genai)!: Interactions models take extra; per-request timeout is seconds and comes to Gemini #6646), so the plugin has one name and one unit everywhere.
  • max_retries instead of retry_options: HttpRetryOptions is a google-genai type, so we flatten it into max_retries, the name the OpenAI and Anthropic SDKs use (Genkit's plugins for them take it through client_options), counting retries after the first attempt. Those SDKs default to 2 retries; we keep google-genai's default of none. Backoff, jitter and status codes keep google-genai's defaults; we can add flat arguments for them if someone needs them. It covers the calls genkit_middleware.Retry can't reach (ai.embed, Veo operation polling, model listing). On model calls the two multiply, so the docstring says to pick one.
  • Named arguments here, client_options on OpenAI and Anthropic: feat(py)!: plugin constructors take keyword arguments and one base_url #6684 gave OpenAI and Anthropic a checked client_options passthrough because their SDK settings are already plain Python (timeout in seconds, max_retries, default_headers, http_client). google-genai keeps the same settings in nested SDK classes (HttpOptions, HttpRetryOptions) with timeouts in milliseconds, so passing them through would bring those types and units back. That's why this PR flattens them instead.
  • http_client_factory takes a function, not a client: An httpx.AsyncClient binds its connection pool to the event loop that first uses it. Genkit runs on more than one loop: genkit start serves the Dev UI from its own thread and asyncio.run (_aio.py), and scripts can call asyncio.run more than once. With a single shared client, a Gemini call on the second loop reached the server and then came back as finish_reason='failed' with an INTERNAL error, so it was billed and genkit_middleware.Retry would re-send it. Genkit wraps the function in loop_local_client and gets the client at call time, so the Dev UI and the app each get their own pool.
  • http_client_factory, not http_client: In the OpenAI and Anthropic SDKs, and in our plugins' client_options={'http_client': ...} passthrough, http_client means an httpx.AsyncClient instance; google-genai takes an instance too (HttpOptions(httpx_async_client=...)). Here it's a zero-arg function, so the same name would mean a different type across plugins, and the natural first try http_client=httpx.AsyncClient(...) would raise. The name says what to pass (the MCP Python SDK uses httpx_client_factory for the same reason), and [py] client_options http_client breaks on a second event loop (OpenAI, Anthropic); Interactions models ignore max_retries genkit-python#206 reuses it for the OpenAI and Anthropic loop fix. No alias for the old name: http_client= fails like any unknown keyword argument.

Breaking changes

  • GoogleAI(http_options=...) and VertexAI(http_options=...) raise TypeError: Move headers, base_url and api_version to top-level keyword arguments on GoogleAI or VertexAI. HttpOptions.timeout is in milliseconds and the new timeout= is in seconds, so divide by 1000: timeout=30000 becomes timeout=30. Passing timeout=30000 unchanged waits over 8 hours. httpx_async_client=client becomes http_client_factory=lambda: httpx.AsyncClient(...), building the client inside the function. retry_options=HttpRetryOptions(attempts=N) becomes max_retries=N - 1, since attempts counts the first try. Custom backoff and status codes aren't exposed. If you never set retry_options, google-genai never retried, and the default is still no retries. client_args, async_client_args, extra_body and base_url_resource_scope have no replacement: pass an http_client_factory for transport settings, and use the model config's extra for per-request body fields.
# before
from google.genai import types as genai_types

GoogleAI(
    http_options=genai_types.HttpOptions(
        headers={'X-Team': 'search'},
        timeout=30000,  # milliseconds
        retry_options=genai_types.HttpRetryOptions(attempts=3),  # counts the first attempt
        httpx_async_client=httpx.AsyncClient(proxy='http://proxy.internal:3128'),
    )
)

# after
GoogleAI(
    headers={'X-Team': 'search'},
    timeout=30,  # seconds
    max_retries=2,  # after the first attempt
    http_client_factory=lambda: httpx.AsyncClient(proxy='http://proxy.internal:3128'),
)
  • GoogleAI(debug_config=...) and VertexAI(debug_config=...) raise TypeError: Pass http_client_factory=lambda: httpx.AsyncClient(transport=...) to record or replay traffic in tests.

Follow-ups

@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 refactors the network configuration in the Google GenAI and Vertex AI plugins by replacing the generic http_options and debug_config parameters with explicit arguments: headers, timeout_seconds, and http_client. It also updates how HTTP options are constructed and copied to ensure safe sharing of the httpx.AsyncClient across requests. Feedback on these changes includes validating that timeout_seconds is non-negative and using a default value in getattr when copying HTTP options to prevent potential AttributeError issues if the underlying SDK model changes.

@huangjeff5
huangjeff5 force-pushed the feat/py-google-genai-network-kwargs branch from 79de868 to a4055e2 Compare October 18, 2026 04:39
@github-actions github-actions Bot added the docs Improvements or additions to documentation label Oct 18, 2026
@huangjeff5
huangjeff5 changed the base branch from feat/py-google-genai-config-surface to fix/py-plugin-tool-choice October 18, 2026 04:39
@huangjeff5
huangjeff5 added this pull request to stack #6827 October 18, 2026 04:40

@cabljac cabljac 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.

A few comments/questions

Base automatically changed from fix/py-plugin-tool-choice to main October 30, 2026 00:48
@huangjeff5
huangjeff5 requested a review from a team as a code owner October 30, 2026 00:48
@huangjeff5 huangjeff5 changed the title feat(py/google-genai)!: GoogleAI and VertexAI take headers, timeout_seconds and http_client feat(py/google-genai)!: GoogleAI and VertexAI take headers, timeout and http_client Oct 30, 2026
@huangjeff5 huangjeff5 changed the title feat(py/google-genai)!: GoogleAI and VertexAI take headers, timeout and http_client feat(py/google-genai)!: GoogleAI and VertexAI take headers, timeout, max_retries and http_client Oct 30, 2026
@huangjeff5
huangjeff5 requested a review from cabljac October 30, 2026 03:15
huangjeff5 added a commit that referenced this pull request Oct 30, 2026
`timeout` on AntigravityConfig, DeepResearchConfig, and LyriaConfig was
milliseconds. It is now float seconds, keeping the name: the standard
library, httpx, requests, aiohttp, and the OpenAI and Anthropic SDKs all
mean seconds by `timeout`, and #6826 makes GoogleAI(timeout=...) seconds
too, so the plugin ends up with one name and one unit. The same applies to
`timeout` in check_operation/cancel_operation `config` for Deep Research,
so one value means the same thing on start, check, and cancel.

0, negative, inf, and NaN raise INVALID_ARGUMENT with the same message as
#6826 ("timeout must be a positive, finite number of seconds"). The field
description and class docstrings carry the ms -> s migration note.

ClientOptions.timeout stays milliseconds on purpose: #6826 builds
ClientOptions(timeout=<ms>) from the plugin's HttpOptions and rewrites
_options.py/_client.py, so the conversion happens once, in
client_overrides_from_config / client_overrides_from_call_config, rounding
up to whole ms like #6826. Dropping the internal ms helper
(_client.timeout_seconds) is a follow-up once both PRs land.

BREAKING CHANGE: config={'timeout': 30000} on Antigravity, Deep Research,
or Interactions Lyria now waits 30000 seconds. Divide by 1000.
huangjeff5 added a commit that referenced this pull request Oct 30, 2026
Follow-ups from a local red-team pass on the seconds change:

- check/cancel `config={'timeout': 'abc'}` (or a list) raised a raw
  TypeError; it now raises INVALID_ARGUMENT. A numeric string like '5' is
  still read as a number, as ClientOptions did before.
- timeout=1e306 passed validation and then hit OverflowError in
  math.ceil; values whose milliseconds overflow now fail validation.
- timeout=True was coerced to 1.0 by pydantic before the after-validator
  ran; a before-validator rejects bool on the configs too.
- round before ceil so 2.007 s is 2007 ms, not 2008.
- docstrings no longer point at GoogleAI(timeout=...), which only exists
  once #6826 lands; README gets the ms -> s migration line.

Tests: case-folded TOOLS / t_o_o_l_s, MCP / file search / search tools
colliding with extra['tools'], extra={'tools': []}, bad timeouts on check
and cancel.
@huangjeff5 huangjeff5 changed the title feat(py/google-genai)!: GoogleAI and VertexAI take headers, timeout, max_retries and http_client feat(py/google-genai)!: GoogleAI and VertexAI take headers, timeout, max_retries and http_client_factory Oct 31, 2026
@huangjeff5
huangjeff5 force-pushed the feat/py-google-genai-network-kwargs branch 2 times, most recently from 6e42a76 to a28da74 Compare November 2, 2026 23:06
@huangjeff5
huangjeff5 force-pushed the feat/py-google-genai-network-kwargs branch from a28da74 to f82a1fc Compare November 3, 2026 02:28
@huangjeff5
huangjeff5 dismissed cabljac’s stale review November 3, 2026 02:29

Addressed comments and approved by hilariie.

@huangjeff5
huangjeff5 merged commit a0d0c36 into main Nov 3, 2026
23 of 24 checks passed
@huangjeff5
huangjeff5 deleted the feat/py-google-genai-network-kwargs branch November 3, 2026 02:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

config docs Improvements or additions to documentation python Python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants