Repository navigation
feat(py/google-genai)!: GoogleAI and VertexAI take headers, timeout, max_retries and http_client_factory - #6826
Merged
Conversation
Contributor
There was a problem hiding this comment.
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
force-pushed
the
feat/py-google-genai-network-kwargs
branch
from
October 18, 2026 04:39
79de868 to
a4055e2
Compare
huangjeff5
changed the base branch from
feat/py-google-genai-config-surface
to
fix/py-plugin-tool-choice
October 18, 2026 04:39
cabljac
previously requested changes
Oct 19, 2026
cabljac
left a comment
Contributor
There was a problem hiding this comment.
A few comments/questions
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.
hilariie
approved these changes
Nov 2, 2026
huangjeff5
force-pushed
the
feat/py-google-genai-network-kwargs
branch
2 times, most recently
from
November 2, 2026 23:06
6e42a76 to
a28da74
Compare
…max_retries and http_client_factory
huangjeff5
force-pushed
the
feat/py-google-genai-network-kwargs
branch
from
November 3, 2026 02:28
a28da74 to
f82a1fc
Compare
huangjeff5
dismissed
cabljac’s stale review
November 3, 2026 02:29
Addressed comments and approved by hilariie.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
GoogleAIandVertexAItake their network settings as plain keyword arguments:headers=,timeout=(seconds),max_retries=andhttp_client_factory=(a function returning anhttpx.AsyncClient), next tobase_url=andapi_version=. Every SDK and Interactions model call goes through a client fromhttp_client_factory, one per event loop. Thehttp_options=anddebug_config=arguments, which tookgoogle-genaiSDK types, are removed.Changes
http_client_factory: Callable[[], httpx.AsyncClient] | None = NoneonGoogleAIandVertexAI: 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 overridebase_url,api_versionorlocation. Genkit never closes these clients. OAuth token refresh (google-auth uses its ownrequeststransport), 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 = NoneonGoogleAIandVertexAI, in seconds: Every request carries this timeout explicitly, so a timeout configured on the client fromhttp_client_factoryis not used. A model config'stimeout(GeminiConfig,AntigravityConfig,DeepResearchConfig,LyriaConfig) overrides it for a single call. Withouttimeout, 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, so0.0001sends 1 ms.max_retries: int | None = NoneonGoogleAIandVertexAI: 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 toHttpRetryOptions(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 = NoneonGoogleAIandVertexAI: Sends extra HTTP headers on every request. On Gemini, Veo, Virtual Try-On and embedders, Genkit appends its attribution tag tox-goog-api-clientanduser-agentcase-insensitively, so{'User-Agent': 'acme'}goes out as one header instead of two. Interactions models (Deep Research, Antigravity, Lyria) replace a caller'sx-goog-api-clientwith Genkit's.http_optionsanddebug_configfromGoogleAIandVertexAI: The constructors no longer exposegoogle-genai'sHttpOptionsandDebugConfigclasses.Decisions
timeoutis in seconds, matching Python convention: We checked what Python developers expect from an argument namedtimeout, 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'sHttpOptions.timeoutis milliseconds because it follows the proto/JS convention, which makes it the outlier in Python. There's no_secondssuffix because in Python the name already means seconds, andhttp_options=raisesTypeError, so everyone migrating has to rewrite the call anyway. The migration note and docstrings call out the ms-to-seconds conversion. Per-requesttimeoutonGeminiConfigand 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_retriesinstead ofretry_options:HttpRetryOptionsis a google-genai type, so we flatten it intomax_retries, the name the OpenAI and Anthropic SDKs use (Genkit's plugins for them take it throughclient_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 callsgenkit_middleware.Retrycan't reach (ai.embed, Veo operation polling, model listing). On model calls the two multiply, so the docstring says to pick one.client_optionson OpenAI and Anthropic: feat(py)!: plugin constructors take keyword arguments and one base_url #6684 gaveOpenAIandAnthropica checkedclient_optionspassthrough because their SDK settings are already plain Python (timeoutin 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_factorytakes a function, not a client: Anhttpx.AsyncClientbinds its connection pool to the event loop that first uses it. Genkit runs on more than one loop:genkit startserves the Dev UI from its own thread andasyncio.run(_aio.py), and scripts can callasyncio.runmore than once. With a single shared client, a Gemini call on the second loop reached the server and then came back asfinish_reason='failed'with an INTERNAL error, so it was billed andgenkit_middleware.Retrywould re-send it. Genkit wraps the function inloop_local_clientand gets the client at call time, so the Dev UI and the app each get their own pool.http_client_factory, nothttp_client: In the OpenAI and Anthropic SDKs, and in our plugins'client_options={'http_client': ...}passthrough,http_clientmeans anhttpx.AsyncClientinstance; 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 tryhttp_client=httpx.AsyncClient(...)would raise. The name says what to pass (the MCP Python SDK useshttpx_client_factoryfor 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=...)andVertexAI(http_options=...)raiseTypeError: Moveheaders,base_urlandapi_versionto top-level keyword arguments onGoogleAIorVertexAI.HttpOptions.timeoutis in milliseconds and the newtimeout=is in seconds, so divide by 1000:timeout=30000becomestimeout=30. Passingtimeout=30000unchanged waits over 8 hours.httpx_async_client=clientbecomeshttp_client_factory=lambda: httpx.AsyncClient(...), building the client inside the function.retry_options=HttpRetryOptions(attempts=N)becomesmax_retries=N - 1, sinceattemptscounts the first try. Custom backoff and status codes aren't exposed. If you never setretry_options, google-genai never retried, and the default is still no retries.client_args,async_client_args,extra_bodyandbase_url_resource_scopehave no replacement: pass anhttp_client_factoryfor transport settings, and use the model config'sextrafor per-request body fields.GoogleAI(debug_config=...)andVertexAI(debug_config=...)raiseTypeError: Passhttp_client_factory=lambda: httpx.AsyncClient(transport=...)to record or replay traffic in tests.Follow-ups
OpenAIandAnthropichave the same event-loop bug throughclient_options={'http_client': ...}. Reproduced: the call on the second loop reaches the server and comes backfailed/UNAVAILABLE. The fix gives them the samehttp_client_factoryas this PR. The same issue also covers Interactions models (Deep Research, Antigravity, Lyria) honoringmax_retries, which they don't yet.