Skip to content

fix(py/google-genai): built-in + function tools, media URL validation, context cache, and timeout floor - #117

Open
huangjeff5 wants to merge 7 commits into
mainfrom
fix/py-1.0-pr4b-google-genai-hardening
Open

huangjeff5 wants to merge 7 commits into
mainfrom
fix/py-1.0-pr4b-google-genai-hardening

Conversation

@huangjeff5

Copy link
Copy Markdown
Collaborator

Bug fixes and edge-case hardening split out of #50, stacked on it. Built-in tools now work next to @ai.tool() functions on Gemini 3, bad media URLs fail before the call instead of in Gemini's 400, context caching works on current model IDs, and short timeout values stop 400ing on the Gemini API.

# --- BEFORE ---
res = await ai.generate(
    model=GoogleAI.gemini('gemini-3-flash-preview'),
    prompt='Is the pad thai safe for a peanut allergy? Check the latest recall notices.',
    tools=[check_allergens],
    config=GeminiConfig(google_search=True, timeout=5.0),
)
# => 400 from Gemini: built-in tools next to function declarations need
#    includeServerSideToolInvocations, and X-Server-Timeout 5 is under the 10s minimum

await ai.generate(prompt=[Part.from_media('./menu.png', content_type='image/png')])
# => 400 from Gemini, echoing the local path back

# --- AFTER ---
# 1. Built-in and function tools share a turn; the 5s deadline is enforced locally
res.text
# => No. The pad thai is garnished with crushed peanuts, and there are no open recalls.

# 2. A local path fails before the call, without echoing the value
await ai.generate(prompt=[Part.from_media('./menu.png', content_type='image/png')])
# => GenkitError: INVALID_ARGUMENT: media url is a local file path; Gemini cannot read local files...

Main Changes

  • Built-in tools work alongside function tools on Gemini 3: Previously, the README hero (google_search plus @ai.tool()) failed with a 400, and extra= couldn't work around it because the field is plugin-managed. Turns that mix google_search, url_context, code_execution, or file_search with function declarations now set toolConfig.includeServerSideToolInvocations=True on the Gemini API (Vertex AI has no such field). The server-side toolCall/toolResponse parts come back as custom.geminiToolCall/custom.geminiToolResponse (JS parity) so the next turn can send them back unchanged. google-genai's automatic function calling is disabled whenever tools are sent, since Genkit runs tools itself.
  • Bad media fails before the call: Previously, local paths, file:// URIs, and raw base64 went to Gemini as fileData and came back in a 400 with the value echoed; a data: URI with no , raised a raw ValueError. These now raise INVALID_ARGUMENT naming the fix (data: URI or uploaded file URI) without the value. Downloads accept gzip/deflate with the 20 MB cap applied after decoding, so a small body can't expand past it. The caller's content_type beats a generic served application/octet-stream, which object stores often send and Gemini rejects.
  • Context caching works on current models and honors context_cache=False: Previously, caching was limited to a hardcoded list of three model IDs (two retired), and GeminiConfig.context_cache was read and dropped. The allowlist is gone (the API rejects models that can't cache), False ignores metadata['cache'] markers for the call, and built-in tools on a cached request raise INVALID_ARGUMENT upfront, as function tools already did.
  • Short timeouts on GoogleAI stop 400ing: Previously, timeout=5 sent X-Server-Timeout: 5, and the Gemini API answers 400 to anything under 10 instead of timing out. The header is now floored at 10 while httpx keeps the exact local deadline, so a 5s timeout succeeds or fails with DEADLINE_EXCEEDED after 5s. Vertex AI accepts shorter values and is unchanged; Interactions models drop the synthetic floor so long runs aren't capped.

Breaking changes

None. custom.geminiToolCall/custom.geminiToolResponse parts only appear on turns that 400ed before this change.

Cross-SDK

The server-side tool parts use the JS plugin's custom.geminiToolCall/custom.geminiToolResponse keys. No changes needed in JS, Go, or Dart.

…s, and raise FAILED_PRECONDITION without a Vertex project

Locks the response and error shapes callers will read after 1.0.

- Candidate metadata: groundingMetadata, urlContextMetadata,
  citationMetadata, logprobsResult, safetyRatings, avgLogprobs,
  finishMessage and tokenCount land at custom['candidates'][i] for
  one-shot and streamed calls; promptFeedback stays at
  custom['promptFeedback']. Streamed logprobs and citations concatenate,
  grounding merges key by key, safetyRatings update per category.
  ModelResponse.finish_message carries candidate 0's finishMessage.
- Streamed final message: adjacent text and reasoning fragments merge
  into one Part each; a fragment with a thought signature closes its
  block and keeps the signature. Chunks still stream unchanged.
- thoughtSignature round-trips on text, media, executableCode and
  codeExecutionResult parts. fileData in a reply becomes a media part,
  a signature-only part becomes signed empty text, and the
  Language/Outcome enums in custom are wire strings. A malformed
  signature is INVALID_ARGUMENT. Gemma history drops reasoning parts
  and signatures, and messages left empty are skipped.
- VertexAI with no project (regional, multi-region, or a per-request
  override) raises GenkitError FAILED_PRECONDITION at call time instead
  of google-genai's bare ValueError, which Retry treated as transient.
  Multi-region no longer raises ValueError at construction.
…ntext cache, and timeout floor

Bug fixes and edge-case hardening split out of #50. No response-shape
or config-schema changes beyond the custom.geminiToolCall and
custom.geminiToolResponse parts that only appear once built-in and
function tools can share a turn.

- Built-in tools next to function tools: on the Gemini API, turns that
  mix google_search, url_context, code_execution or file_search with
  function declarations set toolConfig.includeServerSideToolInvocations.
  The server-side toolCall/toolResponse parts round-trip as
  custom.geminiToolCall/geminiToolResponse with their signature.
  google-genai AFC is disabled whenever tools are sent.
- Media: data: URIs with no ',' or bad base64 raise INVALID_ARGUMENT;
  non-base64 data: URIs are percent-decoded. file://, local paths and
  scheme-less strings raise INVALID_ARGUMENT without echoing the value.
  gzip/deflate downloads are decoded with the 20MB cap applied after
  decoding. The caller's content_type beats a generic served type.
  Tool-response media errors propagate instead of being skipped.
- Context cache: no model allowlist; context_cache=False ignores
  metadata['cache'] markers; built-in tools on a cached request raise
  INVALID_ARGUMENT upfront.
- Timeouts: on the Gemini API, X-Server-Timeout is floored at 10s while
  httpx keeps the shorter local deadline. Interactions drop the
  synthetic floor header. Case-variant custom headers replace instead
  of concatenating.
- Request building skips parts with no Gemini field (Part.data), and
  dict config reads camelCase api_version/base_url/location.
…out floor and server-side tool flag

Keyless GoogleAI() (#49) has no plugin client, so self._client.vertexai
raised AttributeError on a context.secrets call that mixed built-in and
function tools or set a timeout. _is_vertex() falls back to the plugin
kwargs.
@huangjeff5
huangjeff5 added this pull request to stack #109 November 12, 2026 06:52
…alescing, and Vertex project

- Sum logProbabilitySum and tokenCount across stream chunks; token-weight avgLogprobs.
- Join coalesced stream fragments once per run instead of per fragment.
- Decode URL-safe and unpadded thought signatures; drop undecodable ones with a warning.
- Restore ADC project pickup for VertexAI(api_key=..., location=<multi-region>).
- Route Veo and Virtual Try-On per-request clients through the shared builder.
- README: custom is {} when Gemini sends no metadata.
# Conflicts:
#	packages/genkit-google-genai/src/genkit_google_genai/_google.py
#	packages/genkit-google-genai/tests/vertexai_location_test.py
…o HEAD

# Conflicts:
#	packages/genkit-google-genai/tests/part_converter_test.py
Base automatically changed from fix/py-1.0-pr4-google-genai to main December 1, 2026 22:53
# Conflicts:
#	packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py
#	packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py
#	packages/genkit-google-genai/tests/part_converter_fidelity_test.py
#	packages/genkit-google-genai/tests/part_converter_test.py
#	packages/genkit-google-genai/tests/vertexai_project_test.py
@huangjeff5
huangjeff5 requested a review from hilariie December 1, 2026 23:22

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.

1 participant