Skip to content

fix(py/google-genai)!: keep candidate metadata, coalesce streamed parts, and fail fast without a Vertex project - #50

Merged
huangjeff5 merged 4 commits into
mainfrom
fix/py-1.0-pr4-google-genai
Dec 1, 2026
Merged

huangjeff5 merged 4 commits into
mainfrom
fix/py-1.0-pr4-google-genai

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Gemini replies from genkit-google-genai dropped grounding, citation, and logprobs data, streamed turns came back as one Part per chunk, and VertexAI() without a project failed with a bare ValueError that Retry kept retrying. This PR fixes the response and error shapes callers will depend on after 1.0. Bug fixes with no shape change (built-in + function tools, media validation, context cache, timeout floor) moved to #FOLLOWUP.

# --- BEFORE ---
res = await ai.generate(
    model=GoogleAI.gemini('gemini-flash-latest'),
    prompt='Cite recent FDA allergen labeling guidance for sesame.',
    config=GeminiConfig(google_search=True),
)
res.custom
# => {}  (groundingMetadata dropped)

await ai.generate(model=VertexAI.gemini('gemini-2.5-flash'), prompt='Suggest a dish.')
# => ValueError: Project or API key must be set...  (Retry treats it as transient)

# --- AFTER ---
# 1. Candidate metadata lives at res.custom['candidates'][i]
res.custom['candidates'][0]['groundingMetadata']['webSearchQueries']
# => ['FDA sesame allergen labeling guidance']

# 2. A streamed reply is one text Part, not one per chunk
stream = ai.generate_stream(prompt='Describe the tasting menu.')
(await stream.response).message.content
# => [Part(text='Course one is a smoked salmon tartine...')]

# 3. Missing Vertex project fails with a status Retry won't resend
await ai.generate(model=VertexAI.gemini('gemini-2.5-flash'), prompt='Suggest a dish.')
# => GenkitError: FAILED_PRECONDITION: VertexAI has no Google Cloud project. Pass VertexAI(project=...)...

Main Changes

  • Candidate metadata goes to response.custom['candidates'][i]: Previously, only promptFeedback reached custom; groundingMetadata, urlContextMetadata, citationMetadata, logprobsResult, safetyRatings, avgLogprobs, finishMessage, and tokenCount were dropped. One-shot and streamed calls now fill the same layout JS and Go already write, indexed by candidate. Streaming concatenates the per-chunk logprobsResult and citationMetadata lists, sums logProbabilitySum and tokenCount, token-weights avgLogprobs (dropped when more than one chunk sent it and there's nothing to weigh by), and updates safetyRatings per category. groundingMetadata arrives whole on the last chunk in practice; it merges key by key in case Gemini splits it. promptFeedback stays at custom['promptFeedback'], and finish_message is set from candidate 0.
  • A streamed turn's final message is whole parts, not chunks: Previously, response.message.content held every streamed fragment plus a trailing empty text part, so post-model guardrails and history saw split text. Adjacent text and reasoning fragments now merge into one Part each, joined once at stream end; a fragment carrying a thoughtSignature closes its block and keeps the signature. Chunk boundaries are unchanged, but chunk parts go through the same converter, so they pick up the part changes below (signatures in metadata, fileData as media). This has to land before 1.0 because it changes the content list callers index into.
  • thoughtSignature round-trips on every part kind: Previously, the converter kept signatures only on tool requests and reasoning, so Gemini 3 signed text, media, and code parts lost them and the next turn failed. They now survive both directions and JSON persistence. Three shapes change with it: fileData in a reply becomes a media part instead of empty text, a signature-only part becomes signed empty text, and custom.executableCode.language / custom.codeExecutionResult.outcome are the wire strings ('PYTHON', 'OUTCOME_OK') instead of google-genai enum members. Outbound signatures decode from standard or URL-safe base64, padded or not, which covers google-genai's own JSON dump and Gemini's skip_thought_signature_validator placeholder; one that still doesn't decode is dropped with a warning instead of failing the request. Gemma history drops reasoning parts and signatures, since Gemma rejects them.
  • Missing VertexAI project raises FAILED_PRECONDITION: Previously, ADC with no default project surfaced google-genai's ValueError, and Retry retries any exception that isn't a GenkitError. The plugin client and the Gemini, Veo, and Virtual Try-On per-request clients now share one builder and raise GenkitError(status='FAILED_PRECONDITION') naming VertexAI(project=...) and GOOGLE_CLOUD_PROJECT. Multi-region moved from a construction-time ValueError to the same call-time error, so every missing-project path reports one status. With no ADC at all, regional clients still raise UNAUTHENTICATED; multi-region raises FAILED_PRECONDITION, because the plugin needs ADC to find the project and the rep endpoint can't be called without one. VertexAI(api_key=..., location='eu') still picks up the ADC project as before.

Breaking changes

Pre-1.0 shape changes, called out because callers may read them:

  • Streamed response.message.content is coalesced; code that expected one Part per chunk sees fewer parts.
  • custom.executableCode.language and custom.codeExecutionResult.outcome are strings, not enum members.
  • fileData reply parts are media parts, not empty text, in both chunks and the final message.
  • VertexAI(location='eu') with no project no longer raises ValueError at construction; the first call raises GenkitError(FAILED_PRECONDITION).
  • Veo and Virtual Try-On per-request clients (tenant key or base_url / api_version / location override) with no Vertex project raise FAILED_PRECONDITION instead of INVALID_ARGUMENT.

Cross-SDK

ModelResponse.custom on Gemini models now carries candidate metadata, visible in traces and the Dev UI. The layout matches JS (response.custom.candidates[0]) and Go (resp.Custom["candidates"][0]):

// before
{"promptFeedback": {...}}
// after
{"candidates": [{"groundingMetadata": {...}, "citationMetadata": {...}, "safetyRatings": [...]}], "promptFeedback": {...}}

Replies with no candidate metadata or prompt feedback leave custom as {}. JS, Go, and Dart owners need no changes.

@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 0cee093 to 1069b42 Compare November 9, 2026 19:08
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 1069b42 to cadb036 Compare November 9, 2026 19:55
@huangjeff5
huangjeff5 changed the base branch from main to fix/py-1.0-pr4-googleai-byok November 9, 2026 19:55
@huangjeff5
huangjeff5 added this pull request to stack #59 November 9, 2026 19:58
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from cadb036 to 3f2f21f Compare November 9, 2026 20:02
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 3f2f21f to 9b18e5e Compare November 9, 2026 20:21
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 9b18e5e to 1a69ccf Compare November 9, 2026 21:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 1a69ccf to 1e3648e Compare November 9, 2026 21:27
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch 2 times, most recently from 3a2f2c1 to 2da210f Compare November 9, 2026 22:03
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 2da210f to d675ef3 Compare November 9, 2026 23:18
@huangjeff5 huangjeff5 changed the title fix(py/google-genai): URL validation, required tool_choice loop fix, metadata persistence fix(py/google-genai): media URL validation, required tool_choice loop fix, and candidate metadata Nov 10, 2026
@huangjeff5
huangjeff5 requested a review from hilariie November 10, 2026 04:06
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from d675ef3 to 0693e72 Compare November 10, 2026 07:44
@huangjeff5 huangjeff5 changed the title fix(py/google-genai): media URL validation, required tool_choice loop fix, and candidate metadata fix(py/google-genai): tool_choice, candidate metadata, media checks, thought signatures and transport edges Nov 10, 2026
@huangjeff5
huangjeff5 removed this pull request from stack #59 November 10, 2026 18:16
@huangjeff5
huangjeff5 added this pull request to stack #75 November 10, 2026 18:16
@huangjeff5
huangjeff5 removed this pull request from stack #75 November 10, 2026 18:16
@huangjeff5
huangjeff5 added this pull request to stack #76 November 10, 2026 18:16
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 0693e72 to 9beb25b Compare November 10, 2026 18:37
@huangjeff5 huangjeff5 changed the title fix(py/google-genai): nest candidate metadata, fix tool_choice loops and Vertex project checks fix(py/google-genai): keep candidate metadata, stop tool_choice='required' loops, and fail fast without a Vertex project Nov 11, 2026
@huangjeff5
huangjeff5 removed this pull request from stack #88 November 11, 2026 06:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 2ba52f0 to 8bea28f Compare November 11, 2026 06:22
@huangjeff5
huangjeff5 added this pull request to stack #89 November 11, 2026 06:23
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 8bea28f to 5dce93a Compare November 11, 2026 16:21
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from 5dce93a to c29693d Compare November 11, 2026 17:31
@huangjeff5
huangjeff5 removed this pull request from stack #89 November 11, 2026 18:06
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from c29693d to 2139116 Compare November 11, 2026 18:38
@huangjeff5
huangjeff5 added this pull request to stack #109 November 11, 2026 22:25
@huangjeff5 huangjeff5 changed the title fix(py/google-genai): keep candidate metadata, stop tool_choice='required' loops, and fail fast without a Vertex project fix(py/google-genai): keep candidate metadata, validate media/cache/timeouts, and fail fast without a Vertex project Nov 11, 2026
Base automatically changed from fix/py-1.0-pr4-googleai-byok to main November 12, 2026 05:02
…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.
@huangjeff5 huangjeff5 changed the title fix(py/google-genai): keep candidate metadata, validate media/cache/timeouts, and fail fast without a Vertex project fix(py/google-genai): keep candidate metadata, coalesce streamed parts, and fail fast without a Vertex project Nov 12, 2026
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr4-google-genai branch from e5e7c1a to 9f606a1 Compare November 12, 2026 06:38

@hilariie hilariie 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 lines in the description don't match the code: missing ADC gives FAILED_PRECONDITION for multi-region, chunk parts do change (signatures, fileData as media), and the Veo and try-on per-request clients weren't converted. With a Breaking changes section, the title should also have a !.

Comment thread packages/genkit-google-genai/README.md Resolved
…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.
@huangjeff5 huangjeff5 changed the title fix(py/google-genai): keep candidate metadata, coalesce streamed parts, and fail fast without a Vertex project fix(py/google-genai)!: keep candidate metadata, coalesce streamed parts, and fail fast without a Vertex project Nov 16, 2026
@huangjeff5
huangjeff5 requested a review from hilariie November 16, 2026 17:51

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

lgtm with one inline comment

# Conflicts:
#	packages/genkit-google-genai/src/genkit_google_genai/_google.py
#	packages/genkit-google-genai/tests/vertexai_location_test.py
@huangjeff5
huangjeff5 enabled stacked auto-merge (squash) December 1, 2026 22:38
@huangjeff5
huangjeff5 merged commit 2ba55ed into main Dec 1, 2026
21 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-1.0-pr4-google-genai branch December 1, 2026 22:53
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