From 9f606a15318b702a2301d265668b8285419acfa6 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 00:20:20 -0600 Subject: [PATCH 1/3] fix(py/google-genai): keep candidate metadata, coalesce streamed parts, 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. --- packages/genkit-google-genai/README.md | 39 +++ .../src/genkit_google_genai/_google.py | 45 ++- .../genkit_google_genai/_models/_gemini.py | 278 ++++++++++++--- .../src/genkit_google_genai/_models/_utils.py | 89 +++-- .../models/gemini_candidate_metadata_test.py | 321 ++++++++++++++++++ .../tests/part_converter_fidelity_test.py | 261 ++++++++++++++ .../tests/part_converter_test.py | 12 + .../tests/vertexai_location_test.py | 50 +-- .../tests/vertexai_project_test.py | 130 +++++++ 9 files changed, 1128 insertions(+), 97 deletions(-) create mode 100644 packages/genkit-google-genai/tests/models/gemini_candidate_metadata_test.py create mode 100644 packages/genkit-google-genai/tests/part_converter_fidelity_test.py create mode 100644 packages/genkit-google-genai/tests/vertexai_project_test.py diff --git a/packages/genkit-google-genai/README.md b/packages/genkit-google-genai/README.md index 0367bd3bb..7d837cb1c 100644 --- a/packages/genkit-google-genai/README.md +++ b/packages/genkit-google-genai/README.md @@ -240,6 +240,45 @@ config = GeminiTtsConfig( ) ``` +### Search grounding and candidate metadata + +Gemini attaches per-candidate metadata (search sources, citations, URL context, +logprobs, safety ratings) to the reply. Genkit keeps it on `response.custom` +under the wire names: `custom['candidates'][i]` holds `groundingMetadata`, +`urlContextMetadata`, `citationMetadata`, `logprobsResult`, `safetyRatings`, +`avgLogprobs`, `finishMessage` and `tokenCount` for candidate `i`, and +`custom['promptFeedback']` explains a blocked prompt. `custom` is `None` when +Gemini sent neither. Streamed replies merge the chunks' metadata into the same +shape. + +```python +from genkit import Genkit +from genkit_google_genai import GeminiConfig, GoogleAI + +# 1. Initialize Genkit with GoogleAI +ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest')) + + +async def main() -> None: + # 2. Ground the answer in Google Search + response = await ai.generate( + prompt='Which Chicago restaurants earned a new Michelin star this year?', + config=GeminiConfig(google_search=True), + ) + print(response.text) + # => Two Chicago restaurants earned their first star this year: ... + + # 3. List the pages Gemini grounded the answer in + candidates = (response.custom or {}).get('candidates') or [{}] + for chunk in candidates[0].get('groundingMetadata', {}).get('groundingChunks', []): + print(chunk['web']['uri']) + # => https://guide.michelin.com/us/en/illinois/chicago/restaurants + + +if __name__ == '__main__': + ai.run_main(main()) +``` + ### Provider fields the plugin doesn't declare Gemini, Gemini image, and Veo configs reject keys they don't declare, so a diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_google.py b/packages/genkit-google-genai/src/genkit_google_genai/_google.py index 6653be097..a54ad1a74 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -273,6 +273,17 @@ async def _list_genai_models(client: genai.Client, is_vertex: bool) -> GenaiMode } +def _missing_vertex_project_error(cause: BaseException | None = None) -> GenkitError: + return GenkitError( + status='FAILED_PRECONDITION', + message=( + 'VertexAI has no Google Cloud project. Pass VertexAI(project=...), set ' + 'GOOGLE_CLOUD_PROJECT, or run `gcloud auth application-default login` with a default project.' + ), + cause=cause, + ) + + def _plugin_client(client_kwargs: dict[str, Any]) -> genai.Client: """Build the plugin's client on first use in a loop. @@ -280,10 +291,32 @@ def _plugin_client(client_kwargs: dict[str, Any]) -> genai.Client: no project resolves ADC here; a missing or rejected credential becomes UNAUTHENTICATED instead of a bare google.auth error. """ + if ( + client_kwargs.get('vertexai') + and const.is_multi_regional_location(client_kwargs.get('location')) + and not client_kwargs.get('project') + ): + # Multi-regions pin a rep base_url, which makes google-genai skip its + # own project check; fail here with FAILED_PRECONDITION to match regional. + if client_kwargs.get('api_key'): + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + 'Multi-region locations are not available in Vertex AI express mode (api_key). ' + 'Configure the plugin with a project and credentials to use multi-region locations.' + ), + ) + raise _missing_vertex_project_error() try: return genai.client.Client(**client_kwargs) except GOOGLE_AUTH_ERRORS as e: raise_auth_error(e) + except ValueError as e: + # Vertex AI with no project, API key or ADC project: google-genai + # raises a bare ValueError naming its own arguments. + if client_kwargs.get('vertexai') and not client_kwargs.get('project') and not client_kwargs.get('api_key'): + raise _missing_vertex_project_error(e) from e + raise def _call_client(plugin: GoogleAI | VertexAI, context: dict[str, Any] | None) -> genai.Client: @@ -1221,9 +1254,9 @@ def __init__( # Resolve the project here rather than leaving it to the SDK: with any # base_url set the SDK skips its own ADC lookup, and doing it now keeps - # the blocking ADC IO off the event loop. Express mode (api_key) needs no project, so it - # only pays for the probe where a multi-region demands one. - if not self._project and (api_key is None or multi_region): + # the blocking ADC IO off the event loop. Express mode (api_key) needs + # no project; missing projects fail lazily at call time in _plugin_client. + if not self._project and api_key is None: if credentials is not None: self._project = getattr(credentials, 'project_id', None) if not self._project: @@ -1232,12 +1265,6 @@ def __init__( except DefaultCredentialsError: self._project = None - if multi_region and not self._project: - raise ValueError( - 'VertexAI plugin requires a project when using a multi-region location. ' - 'Set the project parameter or GOOGLE_CLOUD_PROJECT environment variable.' - ) - self._client_kwargs: dict[str, Any] = { 'vertexai': self._vertexai, 'api_key': api_key, diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py index c612046dc..19389477c 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py @@ -195,11 +195,165 @@ def _usage_from_metadata(usage_metadata: Any) -> GenerationUsage: # noqa: ANN40 def _custom_from_feedback( feedback: genai_types.GenerateContentResponsePromptFeedback | None, + candidates: list[dict[str, Any]] | None = None, ) -> dict[str, Any] | None: - """The response's ``custom`` payload: the prompt feedback the service sent, if any.""" - if feedback is None: + """The response's ``custom`` payload: ``candidates`` metadata and ``promptFeedback``, if any.""" + custom: dict[str, Any] = {} + if candidates: + custom['candidates'] = candidates + if feedback is not None: + custom['promptFeedback'] = feedback.model_dump(mode='json', by_alias=True, exclude_none=True) + return custom or None + + +# Model-valued candidate fields copied onto custom['candidates'][i] under their wire (camelCase) names. +_CANDIDATE_CUSTOM_FIELDS = ('grounding_metadata', 'url_context_metadata', 'citation_metadata', 'logprobs_result') + + +def _candidate_metadata(candidate: genai_types.Candidate | None) -> dict[str, Any]: + """Candidate-level Gemini metadata on *candidate*, keyed by wire name.""" + if candidate is None: + return {} + out: dict[str, Any] = {} + for field in _CANDIDATE_CUSTOM_FIELDS: + value = getattr(candidate, field, None) + if value is None: + continue + dumped = value.model_dump(mode='json', by_alias=True, exclude_none=True) + if dumped: + out[to_camel(field)] = dumped + if candidate.safety_ratings: + ratings = [ + dumped + for rating in candidate.safety_ratings + if (dumped := rating.model_dump(mode='json', by_alias=True, exclude_none=True)) + ] + if ratings: + out['safetyRatings'] = ratings + if candidate.avg_logprobs is not None: + out['avgLogprobs'] = candidate.avg_logprobs + if candidate.finish_message: + out['finishMessage'] = candidate.finish_message + if candidate.token_count is not None: + out['tokenCount'] = candidate.token_count + return out + + +def _candidates_custom(candidates_by_index: Mapping[int, dict[str, Any]]) -> list[dict[str, Any]] | None: + """Build ``custom['candidates']`` indexed by candidate index, or ``None`` when all are empty.""" + populated = [idx for idx, meta in candidates_by_index.items() if meta] + if not populated: return None - return {'promptFeedback': feedback.model_dump(mode='json', by_alias=True, exclude_none=True)} + return [dict(candidates_by_index.get(idx, {})) for idx in range(max(populated) + 1)] + + +def _merge_safety_ratings(before: list[Any], incoming: list[Any]) -> list[Any]: + """Merge streamed ``safetyRatings`` by ``category`` (latest rating for a category wins).""" + merged = list(before) + by_category: dict[str, int] = { + cat: i + for i, item in enumerate(merged) + if isinstance(item, dict) and isinstance(cat := cast(dict[str, Any], item).get('category'), str) + } + for item in incoming: + cat = cast(dict[str, Any], item).get('category') if isinstance(item, dict) else None + if isinstance(cat, str) and cat in by_category: + merged[by_category[cat]] = item + else: + if isinstance(cat, str): + by_category[cat] = len(merged) + merged.append(item) + return merged + + +def _merge_candidate_metadata(acc: dict[str, Any], chunk: dict[str, Any]) -> None: + """Fold one stream chunk's candidate metadata into *acc*. + + Gemini splits ``groundingMetadata`` across chunks (``webSearchQueries`` and + ``searchEntryPoint`` early, ``groundingChunks`` and ``groundingSupports`` at + the end) and sends ``logprobsResult`` and ``citationMetadata`` lists as + per-chunk deltas. Dict-valued blocks merge key by key, concatenating list + fields and keeping earlier keys that later chunks omit; ``safetyRatings`` + updates per harm category; scalars (``avgLogprobs``, ``finishMessage``, + ``tokenCount``) are latest-wins. + """ + for key, value in chunk.items(): + if value is None: + continue + before = acc.get(key) + if key == 'safetyRatings' and isinstance(before, list) and isinstance(value, list): + acc[key] = _merge_safety_ratings(before, value) + elif isinstance(before, dict) and isinstance(value, dict): + merged = dict(before) + for subkey, subval in value.items(): + if subval is None: + continue + prev_val = merged.get(subkey) + if isinstance(prev_val, list) and isinstance(subval, list): + merged[subkey] = [*prev_val, *subval] + elif isinstance(prev_val, dict) and isinstance(subval, dict): + merged[subkey] = {**prev_val, **subval} + else: + merged[subkey] = subval + acc[key] = merged + else: + acc[key] = value + + +def _coalesce_stream_parts(parts: list[Part]) -> list[Part]: + """Join the text and reasoning fragments a stream delivers into whole parts. + + Adjacent parts of the same kind merge while the earlier one carries no + metadata; the merged part takes the later part's metadata, so a + thought signature that closes a block stays on it. A trailing contentless + signature part attaches its metadata to the preceding unsigned text or + reasoning part. Empty text with no metadata is dropped. Other parts pass + through in order. + """ + out: list[Part] = [] + for part in parts: + kind = 'text' if part.text is not None else 'reasoning' if part.reasoning is not None else None + if kind == 'text' and not part.text and not part.metadata: + continue + prev = out[-1] if out else None + if prev is not None and not prev.metadata: + if kind == 'text' and not part.text and part.metadata and prev.reasoning is not None: + out[-1] = Part.from_reasoning(prev.reasoning, metadata=part.metadata) + continue + if kind is not None and (prev.text is not None if kind == 'text' else prev.reasoning is not None): + if kind == 'text': + out[-1] = Part.from_text((prev.text or '') + (part.text or ''), metadata=part.metadata) + else: + out[-1] = Part.from_reasoning( + (prev.reasoning or '') + (part.reasoning or ''), metadata=part.metadata + ) + continue + out.append(part) + return out or [Part.from_text('')] + + +def _config_value(config: object, snake: str, camel: str | None = None) -> Any: # noqa: ANN401 + """Read *snake* (or *camel* on a Mapping) from a typed or dict config, preserving ``False``.""" + if isinstance(config, Mapping): + mapping = cast(Mapping[str, Any], config) + if snake in mapping: + return mapping[snake] + if camel and camel in mapping: + return mapping[camel] + return None + return getattr(config, snake, None) + + +def _strip_gemma_part(part: Part) -> Part | None: + """Drop reasoning parts and thoughtSignature metadata when replaying history to Gemma.""" + if part.reasoning is not None: + return None + if not part.metadata or 'thoughtSignature' not in part.metadata: + return part + if part.text == '': + return None + clean_meta = {k: v for k, v in part.metadata.items() if k != 'thoughtSignature'} or None + return part.model_copy(update={'metadata': clean_meta}) def _no_candidates_response( @@ -1888,15 +2042,8 @@ async def generate(self, request: ModelRequest, ctx: ModelContext) -> ModelRespo Returns: The model's response to the generation request. """ - model_name = self._version - if request.config: - version = ( - cast(Mapping[str, Any], request.config).get('version') - if isinstance(request.config, Mapping) - else getattr(request.config, 'version', None) - ) - if isinstance(version, str) and version: - model_name = version + version = _config_value(request.config, 'version') + model_name = version if isinstance(version, str) and version else self._version declared_tools, tool_table = self._declare_tools(request) @@ -1985,6 +2132,36 @@ def _tts_needs_default_voice(self, model_name: str) -> bool: return True return model_name.split('/')[-1].lower() in _GEMINI_API_TTS_MODELS_NEEDING_VOICE + @staticmethod + def _plugin_client(kwargs: dict[str, Any]) -> genai.Client: + """Build a request-scoped SDK client, classifying auth and missing-project errors.""" + try: + return genai.Client(**kwargs) + except GOOGLE_AUTH_ERRORS as e: + # A Vertex override with no key or explicit credentials makes the SDK look up ADC. + raise_auth_error(e) + except (ValueError, TypeError) as e: + if ( + isinstance(e, ValueError) + and kwargs.get('vertexai') + and not kwargs.get('project') + and not kwargs.get('api_key') + ): + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + 'VertexAI has no Google Cloud project. Pass VertexAI(project=...), set ' + 'GOOGLE_CLOUD_PROJECT, or run `gcloud auth application-default login` with a default project.' + ), + cause=e, + ) from e + # The SDK rejects bad override combinations (api_key with project, say). + raise GenkitError( + status='INVALID_ARGUMENT', + message='Failed to create google-genai client', + cause=e, + ) from e + async def _resolve_request_client( self, request: ModelRequest, context: dict[str, Any] | None = None ) -> genai.Client: @@ -2060,18 +2237,7 @@ async def _resolve_request_client( 'environment variable.', ) - try: - return genai.Client(**kwargs) - except GOOGLE_AUTH_ERRORS as e: - # A Vertex override with no key or explicit credentials makes the SDK look up ADC. - raise_auth_error(e) - except (ValueError, TypeError) as e: - # The SDK rejects bad override combinations (api_key with project, say). - raise GenkitError( - status='INVALID_ARGUMENT', - message='Failed to create google-genai client', - cause=e, - ) from e + return self._plugin_client(kwargs) async def _generate( self, @@ -2121,8 +2287,15 @@ async def _generate( # The reply is candidate 0, the same one _contents_from_response reads. finish_reason = FinishReason.OTHER - if response.candidates: + finish_message: str | None = None + if response.candidates and response.candidates[0] is not None: finish_reason = _to_finish_reason(response.candidates[0].finish_reason) + finish_message = response.candidates[0].finish_message or None + candidates_custom = _candidates_custom({ + (cand.index if cand.index is not None else pos): _candidate_metadata(cand) + for pos, cand in enumerate(response.candidates) + if cand is not None + }) return ModelResponse( message=Message( @@ -2130,8 +2303,9 @@ async def _generate( role=Role.MODEL, ), finish_reason=finish_reason, + finish_message=finish_message, usage=_usage_from_metadata(response.usage_metadata), - custom=_custom_from_feedback(response.prompt_feedback), + custom=_custom_from_feedback(response.prompt_feedback, candidates_custom), ) async def _streaming_generate( @@ -2161,8 +2335,11 @@ async def _streaming_generate( raise missing_api_key_error() accumulated_content: list[Part] = [] finish_reason = FinishReason.UNKNOWN + finish_message: str | None = None usage_metadata: Any = None prompt_feedback: genai_types.GenerateContentResponsePromptFeedback | None = None + # Grounding rides on the last chunk; logprobs and citations are per-chunk deltas. + candidates_metadata: dict[int, dict[str, Any]] = {} saw_chunk = False saw_candidates = False try: @@ -2188,11 +2365,18 @@ async def _streaming_generate( # The terminating reason and cumulative token usage ride on the trailing # chunks, so hold onto the latest values we see as the stream drains — # otherwise a streamed turn reports no finish reason and no usage at all. - if response_chunk.candidates and response_chunk.candidates[0] is not None: - saw_candidates = True - fr = response_chunk.candidates[0].finish_reason - if fr: - finish_reason = _to_finish_reason(fr) + if response_chunk.candidates: + for pos, cand in enumerate(response_chunk.candidates): + if cand is None: + continue + idx = cand.index if cand.index is not None else pos + if pos == 0: + saw_candidates = True + if cand.finish_reason: + finish_reason = _to_finish_reason(cand.finish_reason) + if cand.finish_message: + finish_message = cand.finish_message + _merge_candidate_metadata(candidates_metadata.setdefault(idx, {}), _candidate_metadata(cand)) if response_chunk.usage_metadata is not None: usage_metadata = response_chunk.usage_metadata if response_chunk.prompt_feedback is not None: @@ -2213,11 +2397,12 @@ async def _streaming_generate( return ModelResponse( message=Message( role=Role.MODEL, - content=accumulated_content, + content=_coalesce_stream_parts(accumulated_content), ), finish_reason=finish_reason, + finish_message=finish_message, usage=_usage_from_metadata(usage_metadata), - custom=_custom_from_feedback(prompt_feedback), + custom=_custom_from_feedback(prompt_feedback, _candidates_custom(candidates_metadata)), ) @cached_property @@ -2260,19 +2445,26 @@ async def _build_messages( """ request_contents: list[genai_types.Content] = [] cache = None + gemma = is_gemma_model(model_name) for msg in request.messages: if msg.role == Role.SYSTEM: continue content_parts: list[genai_types.Part] = [] for p in msg.content: + if gemma: + stripped = _strip_gemma_part(p) + if stripped is None: + continue + p = stripped converted = await PartConverter.to_gemini(p, tools=tools) if isinstance(converted, list): content_parts.extend(converted) else: content_parts.append(converted) role = 'model' if msg.role in (Role.MODEL, 'model') else 'user' - request_contents.append(genai_types.Content(parts=content_parts, role=role)) + if content_parts: + request_contents.append(genai_types.Content(parts=content_parts, role=role)) if msg.metadata and msg.metadata.get('cache'): cache = await self._retrieve_cached_content( @@ -2331,6 +2523,9 @@ async def _genkit_to_googleai_cfg( 5. Build GenerateContentConfig from known fields; leftovers ride on extra_body, and ``config.extra`` is merged over the top of the request body """ + version = _config_value(request.config, 'version') + model_name = version if isinstance(version, str) and version else self._version + gemma = is_gemma_model(model_name) system_instruction: list[genai.types.Part] = [] # 1. System messages @@ -2338,6 +2533,11 @@ async def _genkit_to_googleai_cfg( for m in system_messages: if m.content: for p in m.content: + if gemma: + stripped = _strip_gemma_part(p) + if stripped is None: + continue + p = stripped converted = await PartConverter.to_gemini(p) if isinstance(converted, list): system_instruction.extend(converted) @@ -2394,16 +2594,6 @@ async def _genkit_to_googleai_cfg( cfg = genai_types.GenerateContentConfig() if has_output: - model_name = self._version - if request.config: - version = ( - cast(Mapping[str, Any], request.config).get('version') - if isinstance(request.config, Mapping) - else getattr(request.config, 'version', None) - ) - if isinstance(version, str) and version: - model_name = version - # Check if the model supports constrained generation with this configuration model_info = google_model_info(model_name) model_supports_constrained = ( diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py index 8585331d7..8677a8cc9 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py @@ -48,6 +48,7 @@ """ import base64 +import binascii from collections.abc import Sequence from dataclasses import dataclass from typing import Any, cast @@ -62,6 +63,8 @@ logger = get_logger(__name__) +_ASCII_WHITESPACE = str.maketrans('', '', ' \t\r\n\f\v') + # TODO(#4360): Replace with downloadRequestMedia middleware. # Some media hosts (Wikipedia, for one) answer 403 to requests without a real @@ -192,8 +195,10 @@ async def to_gemini( Returns: A `genai.types.Part` object representing the converted content. """ + signature = cls._extract_thought_signature(part.metadata) if part.text is not None: - return genai.types.Part(text=part.text or ' ') + text = part.text if signature is not None else (part.text or ' ') + return genai.types.Part(text=text, thought_signature=signature) if part.tool_request is not None: args = part.tool_request.input entry = tools.for_original(part.tool_request.name) if tools else None @@ -215,13 +220,13 @@ async def to_gemini( args=args, id=part.tool_request.ref, ), - thought_signature=cls._extract_thought_signature(part.metadata), + thought_signature=signature, ) if part.reasoning is not None: return genai.types.Part( thought=True, text=part.reasoning, - thought_signature=cls._extract_thought_signature(part.metadata), + thought_signature=signature, ) if part.tool_response is not None: tool_response = part.tool_response @@ -296,7 +301,8 @@ async def to_gemini( inline_data=genai.types.Blob( mime_type=mime_type, data=data, - ) + ), + thought_signature=signature, ) if url.startswith('http'): @@ -308,7 +314,8 @@ async def to_gemini( file_data=genai.types.FileData( mime_type=part.media.content_type, file_uri=url, - ) + ), + thought_signature=signature, ) # TODO(#4360): Replace inline download with downloadRequestMedia @@ -321,7 +328,8 @@ async def to_gemini( inline_data=genai.types.Blob( mime_type=mime_type, data=data, - ) + ), + thought_signature=signature, ) # Non-HTTP, non-data URIs (e.g. gs://, Files API URIs) are @@ -330,7 +338,8 @@ async def to_gemini( file_data=genai.types.FileData( mime_type=part.media.content_type, file_uri=url, - ) + ), + thought_signature=signature, ) if part.custom is not None: return cls._to_gemini_custom(part) @@ -351,13 +360,15 @@ def _to_gemini_custom(cls, part: Part) -> genai.types.Part: Returns: A `genai.types.Part` object representing the converted custom content. """ + signature = cls._extract_thought_signature(part.metadata) if part.custom and cls.EXECUTABLE_CODE in part.custom: custom_data = cast(dict, part.custom) return genai.types.Part( executable_code=genai.types.ExecutableCode( code=custom_data[cls.EXECUTABLE_CODE][cls.CODE], language=custom_data[cls.EXECUTABLE_CODE][cls.LANGUAGE], - ) + ), + thought_signature=signature, ) if part.custom and cls.CODE_EXECUTION_RESULT in part.custom: custom_data = cast(dict, part.custom) @@ -365,7 +376,8 @@ def _to_gemini_custom(cls, part: Part) -> genai.types.Part: code_execution_result=genai.types.CodeExecutionResult( outcome=custom_data[cls.CODE_EXECUTION_RESULT][cls.OUTCOME], output=custom_data[cls.CODE_EXECUTION_RESULT][cls.OUTPUT], - ) + ), + thought_signature=signature, ) return genai.types.Part() @@ -386,8 +398,10 @@ def from_gemini(cls, part: genai.types.Part, *, tools: ToolTable | None = None) """ if part.thought: return Part.from_reasoning(part.text or '', metadata=cls._encode_thought_signature(part.thought_signature)) + signature = cls._encode_thought_signature(part.thought_signature) if part.text is not None: - return Part.from_text(part.text) + # Gemini 3 signs text parts too; dropping the signature breaks the next turn. + return Part.from_text(part.text, metadata=signature) if part.function_call: # Tool refs come only from the model's call id. A synthetic part # index isn't unique across turns, so resume can't tell repeated @@ -436,22 +450,38 @@ def from_gemini(cls, part: genai.types.Part, *, tools: ToolTable | None = None) if part.inline_data and part.inline_data.data: b64_data = base64.b64encode(part.inline_data.data).decode('utf-8') return Part.from_media( - f'data:{part.inline_data.mime_type};base64,{b64_data}', content_type=part.inline_data.mime_type + f'data:{part.inline_data.mime_type};base64,{b64_data}', + content_type=part.inline_data.mime_type, + metadata=signature, ) + if part.file_data and part.file_data.file_uri: + return Part.from_media(part.file_data.file_uri, content_type=part.file_data.mime_type, metadata=signature) if part.executable_code: - return Part.from_custom({ - cls.EXECUTABLE_CODE: { - cls.LANGUAGE: part.executable_code.language, - cls.CODE: part.executable_code.code, - } - }) + # Enum members aren't JSON; keep the wire string (PYTHON, OUTCOME_OK). + return Part.from_custom( + { + cls.EXECUTABLE_CODE: { + cls.LANGUAGE: _enum_value(part.executable_code.language), + cls.CODE: part.executable_code.code, + } + }, + metadata=signature, + ) if part.code_execution_result: - return Part.from_custom({ - cls.CODE_EXECUTION_RESULT: { - cls.OUTCOME: part.code_execution_result.outcome, - cls.OUTPUT: part.code_execution_result.output, - } - }) + return Part.from_custom( + { + cls.CODE_EXECUTION_RESULT: { + cls.OUTCOME: _enum_value(part.code_execution_result.outcome), + cls.OUTPUT: part.code_execution_result.output, + } + }, + metadata=signature, + ) + if part.thought_signature: + # A signature with no content (streaming sends these at the end of a + # non-thinking turn): keep as signed empty text so replay doesn't + # invent thought=True and _coalesce_stream_parts folds it onto text. + return Part.from_text('', metadata=signature) return Part.from_text('') @@ -460,7 +490,13 @@ def _extract_thought_signature(cls, metadata: dict[str, Any] | None) -> bytes | """Extracts and decodes the thought signature from metadata.""" thought_sig = metadata.get('thoughtSignature') if metadata else None if isinstance(thought_sig, str): - return base64.b64decode(thought_sig) + try: + return base64.b64decode(thought_sig.translate(_ASCII_WHITESPACE), validate=True) + except (binascii.Error, ValueError) as e: + raise GenkitError( + status='INVALID_ARGUMENT', + message='part metadata.thoughtSignature is not valid base64', + ) from e return None @classmethod @@ -568,5 +604,10 @@ def _redact_url(url: str) -> str: return urlunsplit((parts.scheme, parts.netloc.rpartition('@')[2], parts.path, '', '')) +def _enum_value(value: object) -> object: + """The wire value of a google-genai enum member; anything else unchanged.""" + return getattr(value, 'value', value) + + def _media_too_large(url: str) -> GenkitError: return GenkitError(status='INVALID_ARGUMENT', message=f'media at {_redact_url(url)} is larger than 20MB') diff --git a/packages/genkit-google-genai/tests/models/gemini_candidate_metadata_test.py b/packages/genkit-google-genai/tests/models/gemini_candidate_metadata_test.py new file mode 100644 index 000000000..6f46220b3 --- /dev/null +++ b/packages/genkit-google-genai/tests/models/gemini_candidate_metadata_test.py @@ -0,0 +1,321 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Candidate metadata (grounding, URL context, citations, logprobs, safety, finishMessage) on ModelResponse.custom.""" + +from typing import Any + +import pytest +from genkit_google_genai._models._gemini import GeminiModel +from google.genai import types as genai_types +from pytest_mock import MockerFixture + +from genkit import Message, ModelResponseChunk, Part, Role +from genkit.model import ModelContext, ModelRequest + + +def _request() -> ModelRequest: + return ModelRequest(messages=[Message(role=Role.USER, content=[Part.from_text('Is pesto nut-free?')])]) + + +def _grounding() -> genai_types.GroundingMetadata: + return genai_types.GroundingMetadata( + web_search_queries=['pesto pine nuts'], + grounding_chunks=[ + genai_types.GroundingChunk(web=genai_types.GroundingChunkWeb(uri='https://a.example', title='A')) + ], + ) + + +def _candidate(text: str, **fields: Any) -> genai_types.Candidate: # noqa: ANN401 + return genai_types.Candidate(content=genai_types.Content(parts=[genai_types.Part(text=text)]), **fields) + + +@pytest.mark.asyncio +async def test_generate_nests_candidate_metadata_under_custom_candidates_and_keeps_prompt_feedback_top_level( + mocker: MockerFixture, +) -> None: + """Candidate metadata nests under custom['candidates'][0]; promptFeedback stays top-level.""" + candidate = _candidate( + 'Pesto has pine nuts.', + finish_reason=genai_types.FinishReason.STOP, + finish_message='completed with citations', + token_count=14, + safety_ratings=[ + genai_types.SafetyRating( + category=genai_types.HarmCategory.HARM_CATEGORY_HARASSMENT, + probability=genai_types.HarmProbability.NEGLIGIBLE, + ) + ], + grounding_metadata=_grounding(), + url_context_metadata=genai_types.UrlContextMetadata( + url_metadata=[ + genai_types.UrlMetadata( + retrieved_url='https://a.example', + url_retrieval_status=genai_types.UrlRetrievalStatus.URL_RETRIEVAL_STATUS_SUCCESS, + ) + ] + ), + citation_metadata=genai_types.CitationMetadata(citations=[genai_types.Citation(uri='https://a.example')]), + logprobs_result=genai_types.LogprobsResult( + chosen_candidates=[genai_types.LogprobsResultCandidate(token='Pesto', log_probability=-0.1)] + ), + avg_logprobs=-0.25, + ) + feedback = genai_types.GenerateContentResponsePromptFeedback( + safety_ratings=[ + genai_types.SafetyRating( + category=genai_types.HarmCategory.HARM_CATEGORY_HATE_SPEECH, + probability=genai_types.HarmProbability.NEGLIGIBLE, + ) + ] + ) + client = mocker.AsyncMock() + client.aio.models.generate_content.return_value = genai_types.GenerateContentResponse( + candidates=[candidate], prompt_feedback=feedback + ) + gemini = GeminiModel('gemini-flash-latest', client) + + response = await gemini.generate(_request(), ModelContext()) + + assert response.finish_message == 'completed with citations' + assert response.custom == { + 'candidates': [ + { + 'groundingMetadata': { + 'webSearchQueries': ['pesto pine nuts'], + 'groundingChunks': [{'web': {'uri': 'https://a.example', 'title': 'A'}}], + }, + 'urlContextMetadata': { + 'urlMetadata': [ + {'retrievedUrl': 'https://a.example', 'urlRetrievalStatus': 'URL_RETRIEVAL_STATUS_SUCCESS'} + ] + }, + 'citationMetadata': {'citations': [{'uri': 'https://a.example'}]}, + 'logprobsResult': {'chosenCandidates': [{'token': 'Pesto', 'logProbability': -0.1}]}, + 'safetyRatings': [{'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE'}], + 'avgLogprobs': -0.25, + 'finishMessage': 'completed with citations', + 'tokenCount': 14, + } + ], + 'promptFeedback': {'safetyRatings': [{'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE'}]}, + } + + +@pytest.mark.asyncio +async def test_generate_without_metadata_leaves_custom_unset(mocker: MockerFixture) -> None: + """A plain answer carries no custom payload.""" + client = mocker.AsyncMock() + client.aio.models.generate_content.return_value = genai_types.GenerateContentResponse( + candidates=[_candidate('Yes.', finish_reason=genai_types.FinishReason.STOP)] + ) + gemini = GeminiModel('gemini-flash-latest', client) + + response = await gemini.generate(_request(), ModelContext()) + + assert response.custom in (None, {}) + assert response.finish_message is None + + +@pytest.mark.asyncio +async def test_streaming_generate_keeps_trailing_grounding_under_candidates_and_leaves_chunks_clean( + mocker: MockerFixture, +) -> None: + """Streaming chunks carry content only; aggregated candidate metadata lands on response.custom['candidates'][0].""" + seen_chunks: list[ModelResponseChunk] = [] + + async def chunks() -> Any: # noqa: ANN401 + yield genai_types.GenerateContentResponse(candidates=[_candidate('Pesto ')]) + yield genai_types.GenerateContentResponse( + candidates=[ + _candidate( + 'has pine nuts.', + finish_reason=genai_types.FinishReason.STOP, + finish_message='grounded stop', + grounding_metadata=_grounding(), + ) + ] + ) + + client = mocker.AsyncMock() + client.aio.models.generate_content_stream.return_value = chunks() + gemini = GeminiModel('gemini-flash-latest', client) + + response = await gemini.generate(_request(), ModelContext(streaming_callback=seen_chunks.append)) + + assert [c.custom for c in seen_chunks] == [None, None] + assert response.finish_message == 'grounded stop' + assert response.custom is not None + cand0 = response.custom['candidates'][0] + assert cand0['groundingMetadata']['webSearchQueries'] == ['pesto pine nuts'] + assert cand0['finishMessage'] == 'grounded stop' + + +@pytest.mark.asyncio +async def test_streaming_generate_concatenates_logprobs_citations_and_merges_safety_ratings( + mocker: MockerFixture, +) -> None: + """Logprobs and citations accumulate across chunks; safetyRatings update per category; scalars stay latest-wins.""" + + def logprobs(token: str) -> genai_types.LogprobsResult: + candidate = genai_types.LogprobsResultCandidate(token=token, log_probability=-0.1) + return genai_types.LogprobsResult( + chosen_candidates=[candidate], + top_candidates=[genai_types.LogprobsResultTopCandidates(candidates=[candidate])], + ) + + async def chunks() -> Any: # noqa: ANN401 + yield genai_types.GenerateContentResponse( + candidates=[ + _candidate( + 'Pesto ', + logprobs_result=logprobs('Pesto'), + citation_metadata=genai_types.CitationMetadata( + citations=[genai_types.Citation(uri='https://a.example')] + ), + safety_ratings=[ + genai_types.SafetyRating( + category=genai_types.HarmCategory.HARM_CATEGORY_HATE_SPEECH, + probability=genai_types.HarmProbability.NEGLIGIBLE, + ), + genai_types.SafetyRating( + category=genai_types.HarmCategory.HARM_CATEGORY_HARASSMENT, + probability=genai_types.HarmProbability.NEGLIGIBLE, + ), + ], + avg_logprobs=-0.5, + ) + ] + ) + yield genai_types.GenerateContentResponse( + candidates=[ + _candidate( + 'has pine nuts.', + finish_reason=genai_types.FinishReason.STOP, + logprobs_result=logprobs('has'), + citation_metadata=genai_types.CitationMetadata( + citations=[genai_types.Citation(uri='https://b.example')] + ), + safety_ratings=[ + genai_types.SafetyRating( + category=genai_types.HarmCategory.HARM_CATEGORY_HARASSMENT, + probability=genai_types.HarmProbability.LOW, + ) + ], + avg_logprobs=-0.25, + ) + ] + ) + + client = mocker.AsyncMock() + client.aio.models.generate_content_stream.return_value = chunks() + gemini = GeminiModel('gemini-flash-latest', client) + + response = await gemini.generate(_request(), ModelContext(streaming_callback=mocker.MagicMock())) + + assert response.custom is not None + cand0 = response.custom['candidates'][0] + assert [c['token'] for c in cand0['logprobsResult']['chosenCandidates']] == ['Pesto', 'has'] + assert [t['candidates'][0]['token'] for t in cand0['logprobsResult']['topCandidates']] == ['Pesto', 'has'] + assert [c['uri'] for c in cand0['citationMetadata']['citations']] == [ + 'https://a.example', + 'https://b.example', + ] + assert cand0['safetyRatings'] == [ + {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE'}, + {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'LOW'}, + ] + assert cand0['avgLogprobs'] == -0.25 + + +@pytest.mark.asyncio +async def test_streaming_generate_merges_split_grounding_metadata_keys(mocker: MockerFixture) -> None: + """Gemini streams webSearchQueries/searchEntryPoint early and groundingChunks/groundingSupports later.""" + + async def chunks() -> Any: # noqa: ANN401 + yield genai_types.GenerateContentResponse( + candidates=[ + _candidate( + 'Pesto ', + grounding_metadata=genai_types.GroundingMetadata( + web_search_queries=['pesto pine nuts'], + search_entry_point=genai_types.SearchEntryPoint(rendered_content='
pesto
'), + ), + ) + ] + ) + yield genai_types.GenerateContentResponse( + candidates=[ + _candidate( + 'has pine nuts.', + finish_reason=genai_types.FinishReason.STOP, + grounding_metadata=genai_types.GroundingMetadata( + grounding_chunks=[ + genai_types.GroundingChunk( + web=genai_types.GroundingChunkWeb(uri='https://a.example', title='A') + ) + ], + grounding_supports=[ + genai_types.GroundingSupport(grounding_chunk_indices=[0]), + ], + ), + ) + ] + ) + + client = mocker.AsyncMock() + client.aio.models.generate_content_stream.return_value = chunks() + gemini = GeminiModel('gemini-flash-latest', client) + + response = await gemini.generate(_request(), ModelContext(streaming_callback=mocker.MagicMock())) + + assert response.custom is not None + assert response.custom['candidates'][0]['groundingMetadata'] == { + 'webSearchQueries': ['pesto pine nuts'], + 'searchEntryPoint': {'renderedContent': '
pesto
'}, + 'groundingChunks': [{'web': {'uri': 'https://a.example', 'title': 'A'}}], + 'groundingSupports': [{'groundingChunkIndices': [0]}], + } + + +@pytest.mark.asyncio +async def test_generate_indexes_candidates_list_by_candidate_index(mocker: MockerFixture) -> None: + """Candidate metadata is placed at its candidate index in response.custom['candidates'].""" + first = _candidate('Option A', index=0, finish_reason=genai_types.FinishReason.STOP) + second = _candidate( + 'Option B', + index=1, + finish_reason=genai_types.FinishReason.STOP, + grounding_metadata=_grounding(), + ) + client = mocker.AsyncMock() + client.aio.models.generate_content.return_value = genai_types.GenerateContentResponse(candidates=[first, second]) + gemini = GeminiModel('gemini-flash-latest', client) + + response = await gemini.generate(_request(), ModelContext()) + + assert response.custom == { + 'candidates': [ + {}, + { + 'groundingMetadata': { + 'webSearchQueries': ['pesto pine nuts'], + 'groundingChunks': [{'web': {'uri': 'https://a.example', 'title': 'A'}}], + } + }, + ] + } diff --git a/packages/genkit-google-genai/tests/part_converter_fidelity_test.py b/packages/genkit-google-genai/tests/part_converter_fidelity_test.py new file mode 100644 index 000000000..bf42e40ae --- /dev/null +++ b/packages/genkit-google-genai/tests/part_converter_fidelity_test.py @@ -0,0 +1,261 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""PartConverter fidelity: thought signatures on every part kind, enum values, stream coalescing.""" + +import json +from typing import Any + +import pytest +from genkit_google_genai._models._gemini import GeminiModel, _coalesce_stream_parts +from genkit_google_genai._models._utils import PartConverter +from google.genai import types as genai_types +from pytest_mock import MockerFixture + +from genkit import Message, Part, Role +from genkit.model import ModelContext, ModelRequest + +SIG = b'opaque-signature' + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'gemini_part', + [ + genai_types.Part(text='The eigenvalues sum to 12.', thought_signature=SIG), + genai_types.Part( + executable_code=genai_types.ExecutableCode(code='print(1)', language=genai_types.Language.PYTHON), + thought_signature=SIG, + ), + genai_types.Part( + code_execution_result=genai_types.CodeExecutionResult(outcome=genai_types.Outcome.OUTCOME_OK, output='1\n'), + thought_signature=SIG, + ), + genai_types.Part(inline_data=genai_types.Blob(mime_type='image/png', data=b'\x89PNG'), thought_signature=SIG), + ], + ids=['text', 'executable_code', 'code_execution_result', 'inline_data'], +) +async def test_thought_signature_survives_round_trip(gemini_part: genai_types.Part) -> None: + """Gemini 3 signs text and code parts; the signature must come back on the next turn.""" + genkit_part = PartConverter.from_gemini(gemini_part) + assert genkit_part.metadata is not None and 'thoughtSignature' in genkit_part.metadata + + # JSON persistence (chat history in a DB) must not lose it either. + rehydrated = Part.model_validate_json(genkit_part.model_dump_json(by_alias=True)) + back = await PartConverter.to_gemini(rehydrated) + + assert not isinstance(back, list) + assert back.thought_signature == SIG + assert back == gemini_part + + +def test_code_execution_enums_are_wire_strings() -> None: + """Language/Outcome come back as JSON strings, not google-genai enum members.""" + code = PartConverter.from_gemini( + genai_types.Part(executable_code=genai_types.ExecutableCode(code='x', language=genai_types.Language.PYTHON)) + ) + result = PartConverter.from_gemini( + genai_types.Part(code_execution_result=genai_types.CodeExecutionResult(outcome=genai_types.Outcome.OUTCOME_OK)) + ) + + assert code.custom is not None and result.custom is not None + assert type(code.custom['executableCode']['language']) is str + assert type(result.custom['codeExecutionResult']['outcome']) is str + assert json.loads(code.model_dump_json())['custom']['executableCode']['language'] == 'PYTHON' + + +@pytest.mark.asyncio +async def test_signature_only_part_round_trips_without_inventing_thought_flag() -> None: + """A signature-only part stays signed empty text, so replay sends text='' without thought=True.""" + part = PartConverter.from_gemini(genai_types.Part(thought_signature=SIG)) + + assert part.text == '' + assert part.reasoning is None + assert part.metadata is not None and 'thoughtSignature' in part.metadata + + replayed = await PartConverter.to_gemini(part) + assert not isinstance(replayed, list) + assert replayed.text == '' + assert replayed.thought is None + assert replayed.thought_signature == SIG + + +@pytest.mark.asyncio +async def test_signed_empty_text_is_not_mutated_to_space() -> None: + """Unsigned empty text becomes ' ' for Gemini, but signed empty text keeps '' verbatim.""" + signed = await PartConverter.to_gemini(Part.from_text('', metadata=PartConverter._encode_thought_signature(SIG))) + unsigned = await PartConverter.to_gemini(Part.from_text('')) + + assert not isinstance(signed, list) and not isinstance(unsigned, list) + assert signed.text == '' + assert signed.thought_signature == SIG + assert unsigned.text == ' ' + + +def test_file_data_comes_back_as_media() -> None: + """A fileData part in a response is media, not an empty text part.""" + part = PartConverter.from_gemini( + genai_types.Part(file_data=genai_types.FileData(file_uri='gs://menus/today.pdf', mime_type='application/pdf')) + ) + + assert part.media is not None + assert part.media.url == 'gs://menus/today.pdf' + assert part.media.content_type == 'application/pdf' + + +def test_coalesce_joins_fragments_and_keeps_closing_signature() -> None: + """Text and reasoning fragments merge; the signature that closes a block stays; empty text drops.""" + sig = {'thoughtSignature': 'c2ln'} + parts = [ + Part.from_reasoning('Think '), + Part.from_reasoning('hard.', metadata=sig), + Part.from_text('Pesto '), + Part.from_text('has '), + Part.from_text('pine nuts.'), + Part.from_text(''), + ] + + out = _coalesce_stream_parts(parts) + + assert [p.model_dump(exclude_none=True) for p in out] == [ + {'reasoning': 'Think hard.', 'metadata': sig}, + {'text': 'Pesto has pine nuts.'}, + ] + + +def test_coalesce_does_not_merge_across_signed_part_or_tool_call() -> None: + """A signed part ends a block; tool requests split text runs.""" + sig = {'thoughtSignature': 'c2ln'} + parts = [ + Part.from_text('A', metadata=sig), + Part.from_text('B'), + Part.from_tool_request('lookup_menu', {}), + Part.from_text('C'), + ] + + out = _coalesce_stream_parts(parts) + + assert [p.text for p in out] == ['A', 'B', None, 'C'] + + +@pytest.mark.asyncio +async def test_streaming_final_message_is_coalesced(mocker: MockerFixture) -> None: + """Chunks still stream as fragments; the final message has whole parts for guardrails to read.""" + + def chunk(text: str, **kw: Any) -> genai_types.GenerateContentResponse: # noqa: ANN401 + return genai_types.GenerateContentResponse( + candidates=[genai_types.Candidate(content=genai_types.Content(parts=[genai_types.Part(text=text)]), **kw)] + ) + + async def chunks() -> Any: # noqa: ANN401 + yield chunk('Pesto ') + yield chunk('has pine nuts.') + yield chunk('', finish_reason=genai_types.FinishReason.STOP) + + client = mocker.AsyncMock() + client.aio.models.generate_content_stream.return_value = chunks() + on_chunk = mocker.MagicMock() + + response = await GeminiModel('gemini-flash-latest', client).generate( + ModelRequest(messages=[Message(role=Role.USER, content=[Part.from_text('Nut-free?')])]), + ModelContext(streaming_callback=on_chunk), + ) + + assert response.message is not None + assert [p.text for p in response.message.content] == ['Pesto has pine nuts.'] + assert on_chunk.call_count == 3 + + +@pytest.mark.asyncio +async def test_streaming_trailing_signature_only_chunk_attaches_to_preceding_text(mocker: MockerFixture) -> None: + """A trailing Part(thought_signature=SIG) signs the streamed text instead of emitting thought=True.""" + + async def chunks() -> Any: # noqa: ANN401 + yield genai_types.GenerateContentResponse( + candidates=[genai_types.Candidate(content=genai_types.Content(parts=[genai_types.Part(text='Pesto ')]))] + ) + yield genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate(content=genai_types.Content(parts=[genai_types.Part(text='has pine nuts.')])) + ] + ) + yield genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate( + content=genai_types.Content(parts=[genai_types.Part(thought_signature=SIG)]), + finish_reason=genai_types.FinishReason.STOP, + ) + ] + ) + + client = mocker.AsyncMock() + client.aio.models.generate_content_stream.return_value = chunks() + + response = await GeminiModel('gemini-flash-latest', client).generate( + ModelRequest(messages=[Message(role=Role.USER, content=[Part.from_text('Nut-free?')])]), + ModelContext(streaming_callback=mocker.MagicMock()), + ) + + assert response.message is not None + assert len(response.message.content) == 1 + only = response.message.content[0] + assert only.text == 'Pesto has pine nuts.' + assert only.reasoning is None + replayed = await PartConverter.to_gemini(only) + assert not isinstance(replayed, list) + assert replayed.text == 'Pesto has pine nuts.' + assert replayed.thought is None + assert replayed.thought_signature == SIG + + +@pytest.mark.asyncio +async def test_gemma_history_replay_strips_reasoning_and_thought_signatures(mocker: MockerFixture) -> None: + """Gemma rejects previous thoughts and thoughtSignatures; replay drops reasoning and strips signatures.""" + client = mocker.AsyncMock() + client.aio.models.generate_content.return_value = genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate(content=genai_types.Content(parts=[genai_types.Part(text='Marinara is safe.')])) + ] + ) + sig_meta = PartConverter._encode_thought_signature(SIG) + assert sig_meta is not None + signed_answer = Part.from_text('Pesto has pine nuts.', metadata={**sig_meta, 'source': 'menu'}) + request = ModelRequest( + messages=[ + Message(role=Role.USER, content=[Part.from_text('Is pesto nut-free?')]), + Message( + role=Role.MODEL, + content=[ + Part.from_reasoning('Checking ingredients...', metadata=sig_meta), + signed_answer, + Part.from_text('', metadata=sig_meta), + ], + ), + Message(role=Role.MODEL, content=[Part.from_reasoning('Only thoughts.')]), + Message(role=Role.USER, content=[Part.from_text('What about marinara?')]), + ] + ) + + await GeminiModel('gemma-3-27b-it', client).generate(request, ModelContext()) + + contents = client.aio.models.generate_content.call_args.kwargs['contents'] + assert [(c.role, [(p.text, p.thought, p.thought_signature) for p in c.parts]) for c in contents] == [ + ('user', [('Is pesto nut-free?', None, None)]), + ('model', [('Pesto has pine nuts.', None, None)]), + ('user', [('What about marinara?', None, None)]), + ] + # Caller's Part metadata is not mutated in place. + assert signed_answer.metadata == {**sig_meta, 'source': 'menu'} diff --git a/packages/genkit-google-genai/tests/part_converter_test.py b/packages/genkit-google-genai/tests/part_converter_test.py index 61c46265c..0299e04e5 100644 --- a/packages/genkit-google-genai/tests/part_converter_test.py +++ b/packages/genkit-google-genai/tests/part_converter_test.py @@ -412,3 +412,15 @@ def refuse(request: httpx.Request) -> httpx.Response: with patch('genkit_google_genai._models._utils._media_client', return_value=client): with pytest.raises(httpx.ConnectError): await PartConverter.to_gemini(part) + + +class TestPartValidationEdges: + """A malformed thought signature raises INVALID_ARGUMENT.""" + + @pytest.mark.asyncio + async def test_malformed_thought_signature_is_invalid_argument(self) -> None: + part = Part.from_text('hello', metadata={'thoughtSignature': '%%%not-valid-base64!'}) + with pytest.raises(GenkitError) as raised: + await PartConverter.to_gemini(part) + assert raised.value.status == 'INVALID_ARGUMENT' + assert '%%%not-valid-base64!' not in raised.value.message diff --git a/packages/genkit-google-genai/tests/vertexai_location_test.py b/packages/genkit-google-genai/tests/vertexai_location_test.py index 5b0f02203..3d8bd935f 100644 --- a/packages/genkit-google-genai/tests/vertexai_location_test.py +++ b/packages/genkit-google-genai/tests/vertexai_location_test.py @@ -220,25 +220,32 @@ def test_multi_region_resolves_project_from_adc(self) -> None: assert plugin._project == 'adc-p' assert plugin._client_kwargs['project'] == 'adc-p' - def test_multi_region_without_project_raises(self) -> None: - """A multi-region plugin with no resolvable project fails fast.""" + @pytest.mark.asyncio + async def test_multi_region_without_project_fails_at_call_time(self) -> None: + """A multi-region plugin with no resolvable project constructs lazily and fails at call time.""" with patch.dict(os.environ, {}, clear=True): - with patch('genkit_google_genai._google.genai.client.Client'): - with patch('genkit_google_genai._google.google_auth_default', return_value=(None, None)): - with pytest.raises(ValueError, match='multi-region'): - VertexAI(location='eu') + with patch('genkit_google_genai._google.google_auth_default', return_value=(None, None)): + plugin = VertexAI(location='eu') + assert plugin._project is None + with pytest.raises(GenkitError) as raised: + plugin._runtime_client() + assert raised.value.status == 'FAILED_PRECONDITION' + assert 'VertexAI(project=...)' in raised.value.message - def test_multi_region_no_adc_raises_friendly_error(self) -> None: - """A missing ADC setup surfaces as the friendly ValueError, not a raw auth error.""" + @pytest.mark.asyncio + async def test_multi_region_no_adc_fails_at_call_time(self) -> None: + """A missing ADC setup constructs lazily and surfaces FAILED_PRECONDITION at call time.""" from google.auth.exceptions import DefaultCredentialsError with patch.dict(os.environ, {}, clear=True): - with patch('genkit_google_genai._google.genai.client.Client'): - with patch( - 'genkit_google_genai._google.google_auth_default', side_effect=DefaultCredentialsError('no adc') - ): - with pytest.raises(ValueError, match='multi-region'): - VertexAI(location='eu') + with patch( + 'genkit_google_genai._google.google_auth_default', side_effect=DefaultCredentialsError('no adc') + ): + plugin = VertexAI(location='eu') + assert plugin._project is None + with pytest.raises(GenkitError) as raised: + plugin._runtime_client() + assert raised.value.status == 'FAILED_PRECONDITION' def test_multi_region_uses_credentials_project_id(self) -> None: """Explicit credentials carrying project_id avoid the ADC probe.""" @@ -266,13 +273,16 @@ def test_multi_region_with_pinned_base_url_still_resolves_project(self) -> None: assert plugin._client_kwargs['project'] == 'adc-p' assert plugin._client_kwargs['http_options'].base_url == 'https://example.com/' - def test_multi_region_with_pinned_base_url_without_project_raises(self) -> None: - """A pinned base_url plus multi-region still fails fast without a project.""" + @pytest.mark.asyncio + async def test_multi_region_with_pinned_base_url_without_project_fails_at_call_time(self) -> None: + """A pinned base_url plus multi-region constructs lazily and fails at call time without a project.""" with patch.dict(os.environ, {}, clear=True): - with patch('genkit_google_genai._google.genai.client.Client'): - with patch('genkit_google_genai._google.google_auth_default', return_value=(None, None)): - with pytest.raises(ValueError, match='multi-region'): - VertexAI(location='eu', base_url='https://example.com/') + with patch('genkit_google_genai._google.google_auth_default', return_value=(None, None)): + plugin = VertexAI(location='eu', base_url='https://example.com/') + assert plugin._project is None + with pytest.raises(GenkitError) as raised: + plugin._runtime_client() + assert raised.value.status == 'FAILED_PRECONDITION' class TestRealClientHonorsPinnedBaseUrl: diff --git a/packages/genkit-google-genai/tests/vertexai_project_test.py b/packages/genkit-google-genai/tests/vertexai_project_test.py new file mode 100644 index 000000000..3d7e3ffa0 --- /dev/null +++ b/packages/genkit-google-genai/tests/vertexai_project_test.py @@ -0,0 +1,130 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""VertexAI client construction without a resolvable project or credentials.""" + +import os +from unittest.mock import MagicMock, patch + +import pytest +from genkit_google_genai import VertexAI +from genkit_google_genai._google import _plugin_client +from genkit_google_genai._models._gemini import GeminiModel +from google.auth.credentials import AnonymousCredentials +from google.auth.exceptions import DefaultCredentialsError +from google.genai import types as genai_types + +from genkit import Genkit, GenkitError, Message, Part, Role +from genkit.model import ModelRequest + + +def test_vertex_without_project_is_failed_precondition() -> None: + """google-genai's bare ValueError becomes FAILED_PRECONDITION naming VertexAI(project=...).""" + kwargs = { + 'vertexai': True, + 'api_key': None, + 'credentials': None, + 'project': None, + 'location': 'us-central1', + 'http_options': genai_types.HttpOptions(), + } + with ( + patch( + 'genkit_google_genai._google.genai.client.Client', side_effect=ValueError('Project or API key must be set') + ), + pytest.raises(GenkitError) as raised, + ): + _plugin_client(kwargs) + + assert raised.value.status == 'FAILED_PRECONDITION' + assert 'VertexAI(project=...)' in raised.value.message + assert 'GOOGLE_CLOUD_PROJECT' in raised.value.message + + +def test_other_client_value_errors_are_not_rewritten() -> None: + """A ValueError unrelated to a missing Vertex project passes through unchanged.""" + kwargs = {'vertexai': True, 'api_key': None, 'project': 'menu-prod', 'location': 'us-central1'} + with ( + patch('genkit_google_genai._google.genai.client.Client', side_effect=ValueError('bad location')), + pytest.raises(ValueError, match='bad location'), + ): + _plugin_client(kwargs) + + +@pytest.mark.asyncio +@pytest.mark.parametrize('location', [None, 'us'], ids=['regional', 'multi-region']) +async def test_vertex_without_project_fails_at_call_time_not_init(location: str | None) -> None: + """With ADC credentials but no project, VertexAI() and VertexAI(location='us') fail FAILED_PRECONDITION.""" + creds = (AnonymousCredentials(), None) + with ( + patch.dict(os.environ, {}, clear=True), + patch('google.auth.default', return_value=creds), + patch('genkit_google_genai._google.google_auth_default', return_value=creds), + ): + plugin = VertexAI(location=location) if location else VertexAI() + ai = Genkit(plugins=[plugin]) + response = await ai.generate(model='vertexai/gemini-2.5-flash', prompt='Suggest a dish.') + + # init() registers a static catalog without listing, so the failure comes + # from the model call and generate returns it on response.error. + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'VertexAI(project=...)' in response.error.message + + +@pytest.mark.asyncio +async def test_vertex_without_credentials_fails_unauthenticated_at_call_time_not_init() -> None: + """When google.auth.default finds no ADC, VertexAI() constructs cleanly and the call fails UNAUTHENTICATED.""" + no_adc = DefaultCredentialsError('Could not automatically determine credentials.') + with ( + patch.dict(os.environ, {}, clear=True), + patch('google.auth.default', side_effect=no_adc), + patch('genkit_google_genai._google.google_auth_default', side_effect=no_adc), + ): + ai = Genkit(plugins=[VertexAI()]) + response = await ai.generate(model='vertexai/gemini-2.5-flash', prompt='Suggest a dish.') + + assert response.error is not None + assert response.error.status == 'UNAUTHENTICATED' + + +@pytest.mark.asyncio +async def test_gemini_resolve_request_client_missing_project_is_failed_precondition() -> None: + """GeminiModel._resolve_request_client maps a missing Vertex project ValueError to FAILED_PRECONDITION.""" + client = MagicMock() + client.vertexai = True + model = GeminiModel( + 'gemini-2.5-flash', + client, + client_kwargs={'vertexai': True, 'api_key': None, 'project': None, 'location': 'us-central1'}, + ) + with ( + patch('genkit_google_genai._models._gemini._adc_project', return_value=None), + patch( + 'genkit_google_genai._models._gemini.genai.Client', + side_effect=ValueError('Project or API key must be set'), + ), + pytest.raises(GenkitError) as raised, + ): + await model._resolve_request_client( + ModelRequest( + messages=[Message(role=Role.USER, content=[Part.from_text('hi')])], + config={'api_version': 'v1'}, + ) + ) + + assert raised.value.status == 'FAILED_PRECONDITION' + assert 'VertexAI(project=...)' in raised.value.message From ab96ac0448ab60cac3b2905cae1629dc32178b4b Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 10:35:52 -0600 Subject: [PATCH 2/3] fix(py/google-genai): address review on candidate metadata, stream coalescing, 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=). - Route Veo and Virtual Try-On per-request clients through the shared builder. - README: custom is {} when Gemini sends no metadata. --- packages/genkit-google-genai/README.md | 2 +- .../src/genkit_google_genai/_google.py | 40 +--- .../genkit_google_genai/_models/_gemini.py | 224 +++++++++++------- .../_models/_sdk_config.py | 67 ++++++ .../src/genkit_google_genai/_models/_utils.py | 30 ++- .../src/genkit_google_genai/_models/_veo.py | 15 +- .../_models/_virtual_try_on.py | 12 +- .../models/gemini_candidate_metadata_test.py | 96 +++++++- .../tests/part_converter_fidelity_test.py | 37 +++ .../tests/part_converter_test.py | 56 ++++- .../tests/vertexai_location_test.py | 28 ++- .../tests/vertexai_project_test.py | 90 ++++++- 12 files changed, 526 insertions(+), 171 deletions(-) diff --git a/packages/genkit-google-genai/README.md b/packages/genkit-google-genai/README.md index 7d837cb1c..cb6e313dd 100644 --- a/packages/genkit-google-genai/README.md +++ b/packages/genkit-google-genai/README.md @@ -247,7 +247,7 @@ logprobs, safety ratings) to the reply. Genkit keeps it on `response.custom` under the wire names: `custom['candidates'][i]` holds `groundingMetadata`, `urlContextMetadata`, `citationMetadata`, `logprobsResult`, `safetyRatings`, `avgLogprobs`, `finishMessage` and `tokenCount` for candidate `i`, and -`custom['promptFeedback']` explains a blocked prompt. `custom` is `None` when +`custom['promptFeedback']` explains a blocked prompt. `custom` is `{}` when Gemini sent neither. Streamed replies merge the chunks' metadata into the same shape. diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_google.py b/packages/genkit-google-genai/src/genkit_google_genai/_google.py index a54ad1a74..bfc538ea3 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -144,6 +144,9 @@ ) from genkit_google_genai._models._sdk_config import ( check_timeout_seconds, + check_vertex_project, + is_missing_vertex_project, + missing_vertex_project_error, request_client_kwargs, timeout_seconds_to_ms, ) @@ -273,17 +276,6 @@ async def _list_genai_models(client: genai.Client, is_vertex: bool) -> GenaiMode } -def _missing_vertex_project_error(cause: BaseException | None = None) -> GenkitError: - return GenkitError( - status='FAILED_PRECONDITION', - message=( - 'VertexAI has no Google Cloud project. Pass VertexAI(project=...), set ' - 'GOOGLE_CLOUD_PROJECT, or run `gcloud auth application-default login` with a default project.' - ), - cause=cause, - ) - - def _plugin_client(client_kwargs: dict[str, Any]) -> genai.Client: """Build the plugin's client on first use in a loop. @@ -291,22 +283,7 @@ def _plugin_client(client_kwargs: dict[str, Any]) -> genai.Client: no project resolves ADC here; a missing or rejected credential becomes UNAUTHENTICATED instead of a bare google.auth error. """ - if ( - client_kwargs.get('vertexai') - and const.is_multi_regional_location(client_kwargs.get('location')) - and not client_kwargs.get('project') - ): - # Multi-regions pin a rep base_url, which makes google-genai skip its - # own project check; fail here with FAILED_PRECONDITION to match regional. - if client_kwargs.get('api_key'): - raise GenkitError( - status='FAILED_PRECONDITION', - message=( - 'Multi-region locations are not available in Vertex AI express mode (api_key). ' - 'Configure the plugin with a project and credentials to use multi-region locations.' - ), - ) - raise _missing_vertex_project_error() + check_vertex_project(client_kwargs) try: return genai.client.Client(**client_kwargs) except GOOGLE_AUTH_ERRORS as e: @@ -314,8 +291,8 @@ def _plugin_client(client_kwargs: dict[str, Any]) -> genai.Client: except ValueError as e: # Vertex AI with no project, API key or ADC project: google-genai # raises a bare ValueError naming its own arguments. - if client_kwargs.get('vertexai') and not client_kwargs.get('project') and not client_kwargs.get('api_key'): - raise _missing_vertex_project_error(e) from e + if is_missing_vertex_project(client_kwargs, e): + raise missing_vertex_project_error(e) from e raise @@ -1255,8 +1232,9 @@ def __init__( # Resolve the project here rather than leaving it to the SDK: with any # base_url set the SDK skips its own ADC lookup, and doing it now keeps # the blocking ADC IO off the event loop. Express mode (api_key) needs - # no project; missing projects fail lazily at call time in _plugin_client. - if not self._project and api_key is None: + # no project, so it only pays for the probe where a multi-region demands + # one. A project still missing fails at call time in _plugin_client. + if not self._project and (api_key is None or multi_region): if credentials is not None: self._project = getattr(credentials, 'project_id', None) if not self._project: diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py index 19389477c..68384dacb 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py @@ -20,12 +20,12 @@ import json import math from collections.abc import Callable, Collection, Iterable, Mapping +from dataclasses import dataclass from datetime import datetime, timedelta, timezone from functools import cached_property from typing import Annotated, Any, Any as JsonAny, Literal, TypeAlias, cast, get_args from genkit_google_genai._auth import GOOGLE_AUTH_ERRORS, raise_auth_error -from genkit_google_genai._constants import is_multi_regional_location from genkit_google_genai._models._context_caching._constants import DEFAULT_TTL from genkit_google_genai._models._context_caching._utils import generate_cache_key, validate_context_cache_request from genkit_google_genai._models._sdk_config import ( @@ -36,6 +36,7 @@ attach_leftovers, check_timeout_seconds, dump_family_config, + new_request_client, reject_bool_timeout, request_client_kwargs, sdk_config_error, @@ -266,38 +267,111 @@ def _merge_safety_ratings(before: list[Any], incoming: list[Any]) -> list[Any]: return merged -def _merge_candidate_metadata(acc: dict[str, Any], chunk: dict[str, Any]) -> None: - """Fold one stream chunk's candidate metadata into *acc*. - - Gemini splits ``groundingMetadata`` across chunks (``webSearchQueries`` and - ``searchEntryPoint`` early, ``groundingChunks`` and ``groundingSupports`` at - the end) and sends ``logprobsResult`` and ``citationMetadata`` lists as - per-chunk deltas. Dict-valued blocks merge key by key, concatenating list - fields and keeping earlier keys that later chunks omit; ``safetyRatings`` - updates per harm category; scalars (``avgLogprobs``, ``finishMessage``, - ``tokenCount``) are latest-wins. - """ - for key, value in chunk.items(): +def _merge_metadata_block(before: dict[str, Any], incoming: dict[str, Any]) -> dict[str, Any]: + """Merge a dict-valued block key by key: lists concatenate, dicts update, the rest is latest-wins.""" + merged = dict(before) + for key, value in incoming.items(): if value is None: continue - before = acc.get(key) - if key == 'safetyRatings' and isinstance(before, list) and isinstance(value, list): - acc[key] = _merge_safety_ratings(before, value) - elif isinstance(before, dict) and isinstance(value, dict): - merged = dict(before) - for subkey, subval in value.items(): - if subval is None: - continue - prev_val = merged.get(subkey) - if isinstance(prev_val, list) and isinstance(subval, list): - merged[subkey] = [*prev_val, *subval] - elif isinstance(prev_val, dict) and isinstance(subval, dict): - merged[subkey] = {**prev_val, **subval} - else: - merged[subkey] = subval - acc[key] = merged + prev = merged.get(key) + if isinstance(prev, list) and isinstance(value, list): + merged[key] = [*prev, *value] + elif isinstance(prev, dict) and isinstance(value, dict): + merged[key] = {**prev, **value} else: - acc[key] = value + merged[key] = value + return merged + + +def _chunk_token_weight(chunk: dict[str, Any]) -> int | None: + """Tokens one chunk's ``avgLogprobs`` averages over: ``tokenCount``, else its chosen logprobs, else unknown.""" + count = chunk.get('tokenCount') + if isinstance(count, int) and not isinstance(count, bool) and count > 0: + return count + logprobs = chunk.get('logprobsResult') + chosen = logprobs.get('chosenCandidates') if isinstance(logprobs, dict) else None + if isinstance(chosen, list) and chosen: + return len(cast(list[Any], chosen)) + return None + + +class _StreamCandidateMetadata: + """One candidate's metadata folded across stream chunks. + + In a live gemini-2.5-flash stream ``groundingMetadata`` arrives whole on + the last chunk; the key-by-key merge only matters if Gemini ever splits + it. ``logprobsResult`` and ``citationMetadata`` are per-chunk deltas: + their lists concatenate and ``logprobsResult.logProbabilitySum`` adds up. + ``tokenCount`` is summed and ``avgLogprobs`` is the token-weighted mean, + so the merged values describe the whole reply. If a chunk's + ``avgLogprobs`` has no token count to weigh it by and more than one chunk + carried one, ``avgLogprobs`` is dropped rather than reported wrong. + ``safetyRatings`` updates per harm category; ``finishMessage`` is + latest-wins. + """ + + def __init__(self) -> None: + self._meta: dict[str, Any] = {} + self._token_count = 0 + self._saw_token_count = False + self._weighted_logprobs = 0.0 + self._avg_weight = 0 + self._avg_chunks = 0 + self._avg_unweighted = False + self._last_avg: float | None = None + + def add(self, chunk: dict[str, Any]) -> None: + avg = chunk.get('avgLogprobs') + if isinstance(avg, int | float) and not isinstance(avg, bool): + self._avg_chunks += 1 + self._last_avg = float(avg) + weight = _chunk_token_weight(chunk) + if weight is None: + self._avg_unweighted = True + else: + self._weighted_logprobs += float(avg) * weight + self._avg_weight += weight + count = chunk.get('tokenCount') + if isinstance(count, int) and not isinstance(count, bool): + self._token_count += count + self._saw_token_count = True + for key, value in chunk.items(): + if value is None or key in ('avgLogprobs', 'tokenCount'): + continue + before = self._meta.get(key) + if key == 'safetyRatings' and isinstance(before, list) and isinstance(value, list): + self._meta[key] = _merge_safety_ratings(before, value) + elif key == 'logprobsResult' and isinstance(before, dict) and isinstance(value, dict): + merged = _merge_metadata_block(before, value) + prev_sum, new_sum = before.get('logProbabilitySum'), value.get('logProbabilitySum') + if isinstance(prev_sum, int | float) and isinstance(new_sum, int | float): + merged['logProbabilitySum'] = prev_sum + new_sum + self._meta[key] = merged + elif isinstance(before, dict) and isinstance(value, dict): + self._meta[key] = _merge_metadata_block(before, value) + else: + self._meta[key] = value + + def result(self) -> dict[str, Any]: + out = dict(self._meta) + if self._avg_chunks == 1 and self._last_avg is not None: + out['avgLogprobs'] = self._last_avg + elif self._avg_chunks > 1 and not self._avg_unweighted and self._avg_weight: + out['avgLogprobs'] = self._weighted_logprobs / self._avg_weight + if self._saw_token_count: + out['tokenCount'] = self._token_count + return out + + +@dataclass +class _StreamRun: + """A run of adjacent same-kind stream fragments, joined once at the end.""" + + kind: str | None + fragments: list[str] + metadata: dict[str, Any] | None + part: Part + merged: bool = False def _coalesce_stream_parts(parts: list[Part]) -> list[Part]: @@ -308,27 +382,36 @@ def _coalesce_stream_parts(parts: list[Part]) -> list[Part]: thought signature that closes a block stays on it. A trailing contentless signature part attaches its metadata to the preceding unsigned text or reasoning part. Empty text with no metadata is dropped. Other parts pass - through in order. + through in order. Fragments are collected per run and joined once, so the + cost is linear in reply length. """ - out: list[Part] = [] + runs: list[_StreamRun] = [] for part in parts: kind = 'text' if part.text is not None else 'reasoning' if part.reasoning is not None else None if kind == 'text' and not part.text and not part.metadata: continue - prev = out[-1] if out else None + prev = runs[-1] if runs else None if prev is not None and not prev.metadata: - if kind == 'text' and not part.text and part.metadata and prev.reasoning is not None: - out[-1] = Part.from_reasoning(prev.reasoning, metadata=part.metadata) + if kind == 'text' and not part.text and part.metadata and prev.kind == 'reasoning': + prev.metadata = part.metadata + prev.merged = True continue - if kind is not None and (prev.text is not None if kind == 'text' else prev.reasoning is not None): - if kind == 'text': - out[-1] = Part.from_text((prev.text or '') + (part.text or ''), metadata=part.metadata) - else: - out[-1] = Part.from_reasoning( - (prev.reasoning or '') + (part.reasoning or ''), metadata=part.metadata - ) + if kind is not None and prev.kind == kind: + prev.fragments.append((part.text if kind == 'text' else part.reasoning) or '') + prev.metadata = part.metadata + prev.merged = True continue - out.append(part) + text = (part.text if kind == 'text' else part.reasoning) if kind is not None else None + runs.append(_StreamRun(kind=kind, fragments=[text or ''], metadata=part.metadata, part=part)) + + out: list[Part] = [] + for run in runs: + if not run.merged: + out.append(run.part) + elif run.kind == 'text': + out.append(Part.from_text(''.join(run.fragments), metadata=run.metadata)) + else: + out.append(Part.from_reasoning(''.join(run.fragments), metadata=run.metadata)) return out or [Part.from_text('')] @@ -2132,36 +2215,6 @@ def _tts_needs_default_voice(self, model_name: str) -> bool: return True return model_name.split('/')[-1].lower() in _GEMINI_API_TTS_MODELS_NEEDING_VOICE - @staticmethod - def _plugin_client(kwargs: dict[str, Any]) -> genai.Client: - """Build a request-scoped SDK client, classifying auth and missing-project errors.""" - try: - return genai.Client(**kwargs) - except GOOGLE_AUTH_ERRORS as e: - # A Vertex override with no key or explicit credentials makes the SDK look up ADC. - raise_auth_error(e) - except (ValueError, TypeError) as e: - if ( - isinstance(e, ValueError) - and kwargs.get('vertexai') - and not kwargs.get('project') - and not kwargs.get('api_key') - ): - raise GenkitError( - status='FAILED_PRECONDITION', - message=( - 'VertexAI has no Google Cloud project. Pass VertexAI(project=...), set ' - 'GOOGLE_CLOUD_PROJECT, or run `gcloud auth application-default login` with a default project.' - ), - cause=e, - ) from e - # The SDK rejects bad override combinations (api_key with project, say). - raise GenkitError( - status='INVALID_ARGUMENT', - message='Failed to create google-genai client', - cause=e, - ) from e - async def _resolve_request_client( self, request: ModelRequest, context: dict[str, Any] | None = None ) -> genai.Client: @@ -2222,22 +2275,7 @@ async def _resolve_request_client( # the SDK rejects the two together -- so the probe is skipped there. if self._is_vertex() and not kwargs.get('project') and not kwargs.get('api_key'): kwargs['project'] = getattr(kwargs.get('credentials'), 'project_id', None) or await _adc_project() - if self._is_vertex() and not kwargs.get('project') and is_multi_regional_location(kwargs.get('location')): - if kwargs.get('api_key'): - raise GenkitError( - status='FAILED_PRECONDITION', - message='Multi-region locations are not available in Vertex AI express ' - 'mode (api_key). Configure the plugin with a project and credentials ' - 'to use multi-region locations.', - ) - raise GenkitError( - status='FAILED_PRECONDITION', - message='A project is required when overriding the location with a ' - 'multi-region. Set the project parameter or GOOGLE_CLOUD_PROJECT ' - 'environment variable.', - ) - - return self._plugin_client(kwargs) + return new_request_client(kwargs) async def _generate( self, @@ -2339,7 +2377,7 @@ async def _streaming_generate( usage_metadata: Any = None prompt_feedback: genai_types.GenerateContentResponsePromptFeedback | None = None # Grounding rides on the last chunk; logprobs and citations are per-chunk deltas. - candidates_metadata: dict[int, dict[str, Any]] = {} + candidates_metadata: dict[int, _StreamCandidateMetadata] = {} saw_chunk = False saw_candidates = False try: @@ -2376,7 +2414,7 @@ async def _streaming_generate( finish_reason = _to_finish_reason(cand.finish_reason) if cand.finish_message: finish_message = cand.finish_message - _merge_candidate_metadata(candidates_metadata.setdefault(idx, {}), _candidate_metadata(cand)) + candidates_metadata.setdefault(idx, _StreamCandidateMetadata()).add(_candidate_metadata(cand)) if response_chunk.usage_metadata is not None: usage_metadata = response_chunk.usage_metadata if response_chunk.prompt_feedback is not None: @@ -2402,7 +2440,9 @@ async def _streaming_generate( finish_reason=finish_reason, finish_message=finish_message, usage=_usage_from_metadata(usage_metadata), - custom=_custom_from_feedback(prompt_feedback, _candidates_custom(candidates_metadata)), + custom=_custom_from_feedback( + prompt_feedback, _candidates_custom({idx: acc.result() for idx, acc in candidates_metadata.items()}) + ), ) @cached_property diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_sdk_config.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_sdk_config.py index fa4f05625..1c11e3bef 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_sdk_config.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_sdk_config.py @@ -20,7 +20,9 @@ from collections.abc import Mapping from typing import Any, cast +from genkit_google_genai._auth import GOOGLE_AUTH_ERRORS, raise_auth_error from genkit_google_genai._constants import is_multi_regional_location, multi_regional_base_url +from google import genai from google.genai import types as genai_types from pydantic import BaseModel, ValidationError @@ -81,6 +83,71 @@ def request_client_kwargs( return kwargs +def missing_vertex_project_error(cause: BaseException | None = None) -> GenkitError: + """FAILED_PRECONDITION for a Vertex AI client with no project to bill.""" + return GenkitError( + status='FAILED_PRECONDITION', + message=( + 'VertexAI has no Google Cloud project. Pass VertexAI(project=...), set ' + 'GOOGLE_CLOUD_PROJECT, or run `gcloud auth application-default login` with a default project.' + ), + cause=cause, + ) + + +def check_vertex_project(client_kwargs: Mapping[str, Any]) -> None: + """Raise FAILED_PRECONDITION for a multi-region Vertex client with no project. + + Multi-regions pin a rep ``base_url``, which makes google-genai skip its own + project check, so the request would go out with no project in the path. + """ + if ( + not client_kwargs.get('vertexai') + or client_kwargs.get('project') + or not is_multi_regional_location(client_kwargs.get('location')) + ): + return + if client_kwargs.get('api_key'): + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + 'Multi-region locations are not available in Vertex AI express mode (api_key) ' + 'without a project. Pass VertexAI(project=...) or set GOOGLE_CLOUD_PROJECT.' + ), + ) + raise missing_vertex_project_error() + + +def is_missing_vertex_project(client_kwargs: Mapping[str, Any], error: BaseException) -> bool: + """Whether google-genai's ``error`` means a Vertex client found no project, API key or ADC project.""" + return ( + isinstance(error, ValueError) + and bool(client_kwargs.get('vertexai')) + and not client_kwargs.get('project') + and not client_kwargs.get('api_key') + ) + + +def new_request_client(client_kwargs: dict[str, Any]) -> genai.Client: + """Build a request-scoped google-genai client with Genkit error statuses. + + A missing Vertex project is FAILED_PRECONDITION, a missing or rejected + credential is UNAUTHENTICATED, and any other construction error is + INVALID_ARGUMENT, since only the caller's overrides differ from the + plugin client that already built. + """ + check_vertex_project(client_kwargs) + try: + return genai.Client(**client_kwargs) + except GOOGLE_AUTH_ERRORS as e: + # A Vertex override with no key or explicit credentials makes the SDK look up ADC. + raise_auth_error(e) + except (ValueError, TypeError) as e: + if is_missing_vertex_project(client_kwargs, e): + raise missing_vertex_project_error(e) from e + raise GenkitError(status='INVALID_ARGUMENT', message='Failed to create google-genai client', cause=e) from e + + def unexpected_config_error(*, action_name: str) -> GenkitError: """Fail when the dump leaf sees a config Action did not produce.""" return GenkitError( diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py index 8677a8cc9..572fc2366 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_utils.py @@ -63,7 +63,10 @@ logger = get_logger(__name__) -_ASCII_WHITESPACE = str.maketrans('', '', ' \t\r\n\f\v') +# URL-safe alphabet to standard, ASCII whitespace removed. google-genai's own +# JSON dump writes URL-safe base64, and so does Gemini's documented +# `skip_thought_signature_validator` placeholder. +_SIGNATURE_TO_STD_B64 = str.maketrans('-_', '+/', ' \t\r\n\f\v') # TODO(#4360): Replace with downloadRequestMedia middleware. @@ -487,17 +490,22 @@ def from_gemini(cls, part: genai.types.Part, *, tools: ToolTable | None = None) @classmethod def _extract_thought_signature(cls, metadata: dict[str, Any] | None) -> bytes | None: - """Extracts and decodes the thought signature from metadata.""" + """Decode ``metadata.thoughtSignature``: standard or URL-safe base64, padded or not. + + An undecodable signature is dropped with a warning rather than failing + the request: text and media parts don't need one, and Gemini reports a + missing signature itself where it does. + """ thought_sig = metadata.get('thoughtSignature') if metadata else None - if isinstance(thought_sig, str): - try: - return base64.b64decode(thought_sig.translate(_ASCII_WHITESPACE), validate=True) - except (binascii.Error, ValueError) as e: - raise GenkitError( - status='INVALID_ARGUMENT', - message='part metadata.thoughtSignature is not valid base64', - ) from e - return None + if not isinstance(thought_sig, str): + return None + normalized = thought_sig.translate(_SIGNATURE_TO_STD_B64) + normalized += '=' * (-len(normalized) % 4) + try: + return base64.b64decode(normalized, validate=True) + except (binascii.Error, ValueError): + logger.warning('Dropping part metadata.thoughtSignature: not valid base64') + return None @classmethod def _encode_thought_signature(cls, thought_signature: bytes | None) -> dict[str, Any] | None: diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py index 493568d6b..0d7dfa161 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py @@ -28,6 +28,7 @@ VEO_MANAGED_BODY_FIELDS, attach_config_extra, dump_family_config, + new_request_client, request_client_kwargs, sdk_config_error, ) @@ -38,7 +39,7 @@ from google.genai.errors import APIError from pydantic import Field, ValidationError, model_validator -from genkit import Failure, FinishReason, GenkitError, Message, ModelResponse, Operation, Part, Role +from genkit import Failure, FinishReason, Message, ModelResponse, Operation, Part, Role from genkit.model import ModelContext, ModelInfo, ModelRequest, ModelSupports from genkit.plugin_api import GenkitConfig @@ -325,17 +326,7 @@ def _client_for_context( base_url=base_url, location=location, ) - try: - return genai.Client(**kwargs) - except GOOGLE_AUTH_ERRORS as e: - raise_auth_error(e) - except (ValueError, TypeError) as e: - # The SDK rejects bad override combinations (api_key with project, say). - raise GenkitError( - status='INVALID_ARGUMENT', - message='Failed to create google-genai client', - cause=e, - ) from e + return new_request_client(kwargs) async def start(self, request: ModelRequest[VeoConfig], ctx: ModelContext) -> Operation: """Start a video generation operation. diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_virtual_try_on.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_virtual_try_on.py index 0ed51b23f..70be6549f 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_virtual_try_on.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_virtual_try_on.py @@ -41,6 +41,7 @@ attach_config_extra, attach_leftovers, dump_family_config, + new_request_client, request_client_kwargs, sdk_config_error, split_sdk_fields, @@ -399,16 +400,7 @@ def _client_for_context( base_url_pinned=self._base_url_pinned, default_vertexai=True, ) - try: - return genai.Client(**kwargs) - except GOOGLE_AUTH_ERRORS as e: - raise_auth_error(e) - except (ValueError, TypeError) as e: - raise GenkitError( - status='INVALID_ARGUMENT', - message='Failed to create google-genai client', - cause=e, - ) from e + return new_request_client(kwargs) async def generate(self, request: ModelRequest[VirtualTryOnConfig], ctx: ModelContext) -> ModelResponse: """Generate try-on images for the tagged person and product media. diff --git a/packages/genkit-google-genai/tests/models/gemini_candidate_metadata_test.py b/packages/genkit-google-genai/tests/models/gemini_candidate_metadata_test.py index 6f46220b3..c83077683 100644 --- a/packages/genkit-google-genai/tests/models/gemini_candidate_metadata_test.py +++ b/packages/genkit-google-genai/tests/models/gemini_candidate_metadata_test.py @@ -127,7 +127,8 @@ async def test_generate_without_metadata_leaves_custom_unset(mocker: MockerFixtu response = await gemini.generate(_request(), ModelContext()) - assert response.custom in (None, {}) + # ModelResponse fills an unset custom with {}, so callers never see None. + assert response.custom == {} assert response.finish_message is None @@ -169,7 +170,7 @@ async def chunks() -> Any: # noqa: ANN401 async def test_streaming_generate_concatenates_logprobs_citations_and_merges_safety_ratings( mocker: MockerFixture, ) -> None: - """Logprobs and citations accumulate across chunks; safetyRatings update per category; scalars stay latest-wins.""" + """Logprobs and citations accumulate across chunks; safetyRatings update per category.""" def logprobs(token: str) -> genai_types.LogprobsResult: candidate = genai_types.LogprobsResultCandidate(token=token, log_probability=-0.1) @@ -239,12 +240,13 @@ async def chunks() -> Any: # noqa: ANN401 {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE'}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'LOW'}, ] - assert cand0['avgLogprobs'] == -0.25 + # One chosen token per chunk, so the reply's average weighs both chunks equally. + assert cand0['avgLogprobs'] == pytest.approx(-0.375) @pytest.mark.asyncio async def test_streaming_generate_merges_split_grounding_metadata_keys(mocker: MockerFixture) -> None: - """Gemini streams webSearchQueries/searchEntryPoint early and groundingChunks/groundingSupports later.""" + """If Gemini ever splits groundingMetadata across chunks, the keys merge instead of the last chunk winning.""" async def chunks() -> Any: # noqa: ANN401 yield genai_types.GenerateContentResponse( @@ -319,3 +321,89 @@ async def test_generate_indexes_candidates_list_by_candidate_index(mocker: Mocke }, ] } + + +@pytest.mark.asyncio +async def test_streaming_generate_sums_logprob_totals_and_token_counts(mocker: MockerFixture) -> None: + """logProbabilitySum and tokenCount add up across chunks; avgLogprobs is token-weighted.""" + + def logprobs(tokens: list[str], total: float) -> genai_types.LogprobsResult: + return genai_types.LogprobsResult( + chosen_candidates=[genai_types.LogprobsResultCandidate(token=t, log_probability=-0.1) for t in tokens], + log_probability_sum=total, + ) + + async def chunks() -> Any: # noqa: ANN401 + yield genai_types.GenerateContentResponse( + candidates=[ + _candidate( + 'Pesto has ', + logprobs_result=logprobs(['Pesto', 'has'], -1.0), + avg_logprobs=-0.5, + token_count=2, + ) + ] + ) + yield genai_types.GenerateContentResponse( + candidates=[ + _candidate( + 'pine nuts.', + finish_reason=genai_types.FinishReason.STOP, + logprobs_result=logprobs(['pine', 'nuts', '.'], -0.6), + avg_logprobs=-0.2, + token_count=3, + ) + ] + ) + + client = mocker.AsyncMock() + client.aio.models.generate_content_stream.return_value = chunks() + gemini = GeminiModel('gemini-flash-latest', client) + + response = await gemini.generate(_request(), ModelContext(streaming_callback=mocker.MagicMock())) + + assert response.custom is not None + cand0 = response.custom['candidates'][0] + assert cand0['logprobsResult']['logProbabilitySum'] == pytest.approx(-1.6) + assert len(cand0['logprobsResult']['chosenCandidates']) == 5 + assert cand0['tokenCount'] == 5 + assert cand0['avgLogprobs'] == pytest.approx(-1.6 / 5) + + +@pytest.mark.asyncio +async def test_streaming_generate_drops_avg_logprobs_it_cannot_weigh(mocker: MockerFixture) -> None: + """Chunk averages with no token count or logprobs to weigh them by aren't reported as the reply's average.""" + + async def chunks() -> Any: # noqa: ANN401 + yield genai_types.GenerateContentResponse(candidates=[_candidate('Pesto ', avg_logprobs=-0.5)]) + yield genai_types.GenerateContentResponse( + candidates=[_candidate('has pine nuts.', finish_reason=genai_types.FinishReason.STOP, avg_logprobs=-0.2)] + ) + + client = mocker.AsyncMock() + client.aio.models.generate_content_stream.return_value = chunks() + gemini = GeminiModel('gemini-flash-latest', client) + + response = await gemini.generate(_request(), ModelContext(streaming_callback=mocker.MagicMock())) + + assert 'avgLogprobs' not in (response.custom or {}).get('candidates', [{}])[0] + + +@pytest.mark.asyncio +async def test_streaming_generate_keeps_single_chunk_avg_logprobs(mocker: MockerFixture) -> None: + """One chunk with avgLogprobs passes it through unchanged, as a one-shot call would.""" + + async def chunks() -> Any: # noqa: ANN401 + yield genai_types.GenerateContentResponse(candidates=[_candidate('Pesto ')]) + yield genai_types.GenerateContentResponse( + candidates=[_candidate('has pine nuts.', finish_reason=genai_types.FinishReason.STOP, avg_logprobs=-0.2)] + ) + + client = mocker.AsyncMock() + client.aio.models.generate_content_stream.return_value = chunks() + gemini = GeminiModel('gemini-flash-latest', client) + + response = await gemini.generate(_request(), ModelContext(streaming_callback=mocker.MagicMock())) + + assert response.custom is not None + assert response.custom['candidates'][0]['avgLogprobs'] == -0.2 diff --git a/packages/genkit-google-genai/tests/part_converter_fidelity_test.py b/packages/genkit-google-genai/tests/part_converter_fidelity_test.py index bf42e40ae..4b04cf592 100644 --- a/packages/genkit-google-genai/tests/part_converter_fidelity_test.py +++ b/packages/genkit-google-genai/tests/part_converter_fidelity_test.py @@ -151,6 +151,43 @@ def test_coalesce_does_not_merge_across_signed_part_or_tool_call() -> None: assert [p.text for p in out] == ['A', 'B', None, 'C'] +def test_coalesce_builds_each_merged_part_once(mocker: MockerFixture) -> None: + """A long stream joins its fragments once per run instead of rebuilding the part per fragment.""" + parts = [Part.from_text('crumb ') for _ in range(2000)] + parts.append(Part.from_text('end.', metadata={'thoughtSignature': 'c2ln'})) + from_text = mocker.spy(Part, 'from_text') + + out = _coalesce_stream_parts(parts) + + assert from_text.call_count == 1 + assert len(out) == 1 + assert out[0].text == 'crumb ' * 2000 + 'end.' + assert out[0].metadata == {'thoughtSignature': 'c2ln'} + + +def test_coalesce_attaches_trailing_signature_to_reasoning() -> None: + """A contentless signed part after unsigned reasoning signs the reasoning block.""" + sig = {'thoughtSignature': 'c2ln'} + out = _coalesce_stream_parts([ + Part.from_reasoning('Check '), + Part.from_reasoning('allergens.'), + Part.from_text('', metadata=sig), + ]) + + assert [p.model_dump(exclude_none=True) for p in out] == [{'reasoning': 'Check allergens.', 'metadata': sig}] + + +def test_coalesce_passes_unmerged_parts_through_unchanged() -> None: + """A part with nothing to merge into is the same object, not a rebuilt copy.""" + tool = Part.from_tool_request('lookup_menu', {}) + text = Part.from_text('Pesto.') + + out = _coalesce_stream_parts([tool, text]) + + assert out[0] is tool + assert out[1] is text + + @pytest.mark.asyncio async def test_streaming_final_message_is_coalesced(mocker: MockerFixture) -> None: """Chunks still stream as fragments; the final message has whole parts for guardrails to read.""" diff --git a/packages/genkit-google-genai/tests/part_converter_test.py b/packages/genkit-google-genai/tests/part_converter_test.py index 0299e04e5..d4dbd0678 100644 --- a/packages/genkit-google-genai/tests/part_converter_test.py +++ b/packages/genkit-google-genai/tests/part_converter_test.py @@ -414,13 +414,55 @@ def refuse(request: httpx.Request) -> httpx.Response: await PartConverter.to_gemini(part) -class TestPartValidationEdges: - """A malformed thought signature raises INVALID_ARGUMENT.""" +class TestThoughtSignatureDecoding: + """Signatures decode from standard or URL-safe base64; a bad one is dropped, not fatal.""" @pytest.mark.asyncio - async def test_malformed_thought_signature_is_invalid_argument(self) -> None: + async def test_malformed_thought_signature_is_dropped_not_fatal(self) -> None: part = Part.from_text('hello', metadata={'thoughtSignature': '%%%not-valid-base64!'}) - with pytest.raises(GenkitError) as raised: - await PartConverter.to_gemini(part) - assert raised.value.status == 'INVALID_ARGUMENT' - assert '%%%not-valid-base64!' not in raised.value.message + + back = await PartConverter.to_gemini(part) + + assert not isinstance(back, list) + assert back.text == 'hello' + assert back.thought_signature is None + + @pytest.mark.asyncio + @pytest.mark.parametrize( + 'part', + [ + Part.from_text('hello', metadata={'thoughtSignature': 'skip_thought_signature_validator'}), + Part.from_tool_request( + 'lookup_menu', {}, metadata={'thoughtSignature': 'skip_thought_signature_validator'} + ), + ], + ids=['text', 'tool_request'], + ) + async def test_skip_validator_placeholder_round_trips(self, part: Part) -> None: + """Gemini's documented placeholder is URL-safe base64 and reaches the wire unchanged.""" + back = await PartConverter.to_gemini(part) + + assert not isinstance(back, list) + assert back.thought_signature is not None + assert ( + back.model_dump(mode='json', exclude_none=True)['thought_signature'] == 'skip_thought_signature_validator' + ) + + @pytest.mark.asyncio + async def test_sdk_json_dump_signature_decodes(self) -> None: + """google-genai writes URL-safe base64 when it dumps a Part to JSON; that string decodes back.""" + sig = bytes([0xFB, 0xFF, 0xBF, 0x00]) + dumped = genai.types.Part(text='hi', thought_signature=sig).model_dump(mode='json')['thought_signature'] + assert '-' in dumped or '_' in dumped + + back = await PartConverter.to_gemini(Part.from_text('hi', metadata={'thoughtSignature': dumped})) + + assert not isinstance(back, list) + assert back.thought_signature == sig + + @pytest.mark.asyncio + async def test_unpadded_signature_decodes(self) -> None: + back = await PartConverter.to_gemini(Part.from_text('hi', metadata={'thoughtSignature': 'c2lnbg'})) + + assert not isinstance(back, list) + assert back.thought_signature == b'sign' diff --git a/packages/genkit-google-genai/tests/vertexai_location_test.py b/packages/genkit-google-genai/tests/vertexai_location_test.py index 3d8bd935f..84259ef24 100644 --- a/packages/genkit-google-genai/tests/vertexai_location_test.py +++ b/packages/genkit-google-genai/tests/vertexai_location_test.py @@ -27,6 +27,7 @@ multi_regional_base_url, vertex_api_host, ) +from genkit_google_genai._google import _plugin_client as _google_plugin_client from genkit_google_genai._models import _gemini as gemini_module from genkit_google_genai._models._gemini import GeminiConfig, GeminiModel from google import genai @@ -220,6 +221,29 @@ def test_multi_region_resolves_project_from_adc(self) -> None: assert plugin._project == 'adc-p' assert plugin._client_kwargs['project'] == 'adc-p' + def test_api_key_multi_region_resolves_project_from_adc(self) -> None: + """Express mode on a multi-region still picks up the ADC project, since the rep endpoint needs one.""" + with patch.dict(os.environ, {}, clear=True): + with patch('genkit_google_genai._google.google_auth_default', return_value=(None, 'adc-p')) as adc: + plugin = VertexAI(api_key='k', location='eu') + client = _google_plugin_client(plugin._client_kwargs) + adc.assert_called_once() + assert plugin._client_kwargs['project'] == 'adc-p' + assert client._api_client.project == 'adc-p' + assert client._api_client.api_key == 'k' + + @pytest.mark.asyncio + async def test_api_key_multi_region_without_project_is_express_mode_error(self) -> None: + """Express mode on a multi-region with no ADC project fails FAILED_PRECONDITION at call time.""" + with patch.dict(os.environ, {}, clear=True): + with patch('genkit_google_genai._google.google_auth_default', return_value=(None, None)): + plugin = VertexAI(api_key='k', location='eu') + with pytest.raises(GenkitError) as raised: + plugin._runtime_client() + assert raised.value.status == 'FAILED_PRECONDITION' + assert 'express mode' in raised.value.message + assert 'k' not in raised.value.message.split() + @pytest.mark.asyncio async def test_multi_region_without_project_fails_at_call_time(self) -> None: """A multi-region plugin with no resolvable project constructs lazily and fails at call time.""" @@ -440,7 +464,7 @@ async def test_multi_region_override_without_project_raises(self) -> None: model = _vertex_model() model._client_kwargs = dict(model._client_kwargs, project=None) with patch('genkit_google_genai._models._gemini.google_auth_default', return_value=(None, None)): - with pytest.raises(GenkitError, match='project is required'): + with pytest.raises(GenkitError, match=r'VertexAI\(project=\.\.\.\)'): await model._resolve_request_client(_text_request({'location': 'eu'})) @pytest.mark.asyncio @@ -453,7 +477,7 @@ async def test_multi_region_override_no_adc_raises_friendly_error(self) -> None: with patch( 'genkit_google_genai._models._gemini.google_auth_default', side_effect=DefaultCredentialsError('no adc') ): - with pytest.raises(GenkitError, match='project is required'): + with pytest.raises(GenkitError, match=r'VertexAI\(project=\.\.\.\)'): await model._resolve_request_client(_text_request({'location': 'eu'})) @pytest.mark.asyncio diff --git a/packages/genkit-google-genai/tests/vertexai_project_test.py b/packages/genkit-google-genai/tests/vertexai_project_test.py index 3d7e3ffa0..e2b0fcba7 100644 --- a/packages/genkit-google-genai/tests/vertexai_project_test.py +++ b/packages/genkit-google-genai/tests/vertexai_project_test.py @@ -23,12 +23,14 @@ from genkit_google_genai import VertexAI from genkit_google_genai._google import _plugin_client from genkit_google_genai._models._gemini import GeminiModel +from genkit_google_genai._models._veo import VeoModel +from genkit_google_genai._models._virtual_try_on import VirtualTryOnModel from google.auth.credentials import AnonymousCredentials from google.auth.exceptions import DefaultCredentialsError from google.genai import types as genai_types from genkit import Genkit, GenkitError, Message, Part, Role -from genkit.model import ModelRequest +from genkit.model import ModelContext, ModelRequest def test_vertex_without_project_is_failed_precondition() -> None: @@ -64,6 +66,36 @@ def test_other_client_value_errors_are_not_rewritten() -> None: _plugin_client(kwargs) +def test_express_mode_value_error_is_not_rewritten_as_missing_project() -> None: + """With an api_key, a google-genai ValueError isn't a missing project and passes through.""" + kwargs = {'vertexai': True, 'api_key': 'k', 'project': None, 'location': 'us-central1'} + with ( + patch('genkit_google_genai._google.genai.client.Client', side_effect=ValueError('bad http_options')), + pytest.raises(ValueError, match='bad http_options'), + ): + _plugin_client(kwargs) + + +def test_express_mode_multi_region_without_project_is_failed_precondition() -> None: + """api_key on a multi-region with no project fails before google-genai sends a project-less request.""" + kwargs = {'vertexai': True, 'api_key': 'k', 'project': None, 'location': 'eu'} + with patch('genkit_google_genai._google.genai.client.Client') as ctor, pytest.raises(GenkitError) as raised: + _plugin_client(kwargs) + + ctor.assert_not_called() + assert raised.value.status == 'FAILED_PRECONDITION' + assert 'express mode' in raised.value.message + + +def test_express_mode_multi_region_with_project_builds_client() -> None: + """api_key plus a project on a multi-region is a valid client, not the express-mode error.""" + kwargs = {'vertexai': True, 'api_key': 'k', 'project': 'menu-prod', 'location': 'eu'} + with patch('genkit_google_genai._google.genai.client.Client') as ctor: + _plugin_client(kwargs) + + ctor.assert_called_once_with(**kwargs) + + @pytest.mark.asyncio @pytest.mark.parametrize('location', [None, 'us'], ids=['regional', 'multi-region']) async def test_vertex_without_project_fails_at_call_time_not_init(location: str | None) -> None: @@ -128,3 +160,59 @@ async def test_gemini_resolve_request_client_missing_project_is_failed_precondit assert raised.value.status == 'FAILED_PRECONDITION' assert 'VertexAI(project=...)' in raised.value.message + + +@pytest.mark.asyncio +async def test_veo_request_client_missing_project_is_failed_precondition() -> None: + """Veo's per-request client reports a missing Vertex project the same way as Gemini's.""" + model = VeoModel( + 'veo-3.0-generate-001', + MagicMock(vertexai=True), + client_kwargs={'vertexai': True, 'api_key': None, 'project': None, 'location': 'us-central1'}, + ) + with ( + patch( + 'genkit_google_genai._models._veo.genai.Client', side_effect=ValueError('Project or API key must be set') + ), + pytest.raises(GenkitError) as raised, + ): + model._client_for_context(ModelContext(context={}), config={'api_version': 'v1'}) + + assert raised.value.status == 'FAILED_PRECONDITION' + assert 'VertexAI(project=...)' in raised.value.message + + +@pytest.mark.asyncio +async def test_virtual_try_on_request_client_missing_project_is_failed_precondition() -> None: + """Virtual Try-On's per-request client reports a missing Vertex project the same way as Gemini's.""" + model = VirtualTryOnModel( + 'virtual-try-on-preview-08-04', + MagicMock(vertexai=True), + client_kwargs={'vertexai': True, 'api_key': None, 'project': None, 'location': 'us-central1'}, + ) + with ( + patch( + 'genkit_google_genai._models._virtual_try_on.genai.Client', + side_effect=ValueError('Project or API key must be set'), + ), + pytest.raises(GenkitError) as raised, + ): + model._client_for_context(ModelContext(context={}), config={'api_version': 'v1'}) + + assert raised.value.status == 'FAILED_PRECONDITION' + assert 'VertexAI(project=...)' in raised.value.message + + +@pytest.mark.asyncio +async def test_veo_multi_region_override_without_project_is_failed_precondition() -> None: + """A multi-region location override with no project fails before the SDK sends a project-less request.""" + model = VeoModel( + 'veo-3.0-generate-001', + MagicMock(vertexai=True), + client_kwargs={'vertexai': True, 'api_key': None, 'project': None, 'location': 'us-central1'}, + ) + with patch('genkit_google_genai._models._veo.genai.Client') as ctor, pytest.raises(GenkitError) as raised: + model._client_for_context(ModelContext(context={}), config={'location': 'eu'}) + + ctor.assert_not_called() + assert raised.value.status == 'FAILED_PRECONDITION' From ba9733cea0d10abf0427a713256acabf718ba548 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 1 Dec 2026 22:30:29 +0000 Subject: [PATCH 3/3] test(google-genai): exercise + and / base64 chars in thought signature fixture --- .../genkit-google-genai/tests/part_converter_fidelity_test.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/genkit-google-genai/tests/part_converter_fidelity_test.py b/packages/genkit-google-genai/tests/part_converter_fidelity_test.py index 4b04cf592..8b3f239f1 100644 --- a/packages/genkit-google-genai/tests/part_converter_fidelity_test.py +++ b/packages/genkit-google-genai/tests/part_converter_fidelity_test.py @@ -28,7 +28,9 @@ from genkit import Message, Part, Role from genkit.model import ModelContext, ModelRequest -SIG = b'opaque-signature' +# Encodes with '+' and '/' in standard base64 ('+//+b3BhcXVlLXNpZ25hdHVyZQ=='), +# so round-trip tests exercise the standard alphabet (not just alphanumeric bytes). +SIG = b'\xfb\xff\xfeopaque-signature' @pytest.mark.asyncio