From 9f606a15318b702a2301d265668b8285419acfa6 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 00:20:20 -0600 Subject: [PATCH 1/4] 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 6fb7fb76dbaae85e4a3e49eba08460b9ca8dac03 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 00:20:51 -0600 Subject: [PATCH 2/4] fix(py/google-genai): built-in + function tools, media validation, context cache, and timeout floor Bug fixes and edge-case hardening split out of #50. No response-shape or config-schema changes beyond the custom.geminiToolCall and custom.geminiToolResponse parts that only appear once built-in and function tools can share a turn. - Built-in tools next to function tools: on the Gemini API, turns that mix google_search, url_context, code_execution or file_search with function declarations set toolConfig.includeServerSideToolInvocations. The server-side toolCall/toolResponse parts round-trip as custom.geminiToolCall/geminiToolResponse with their signature. google-genai AFC is disabled whenever tools are sent. - Media: data: URIs with no ',' or bad base64 raise INVALID_ARGUMENT; non-base64 data: URIs are percent-decoded. file://, local paths and scheme-less strings raise INVALID_ARGUMENT without echoing the value. gzip/deflate downloads are decoded with the 20MB cap applied after decoding. The caller's content_type beats a generic served type. Tool-response media errors propagate instead of being skipped. - Context cache: no model allowlist; context_cache=False ignores metadata['cache'] markers; built-in tools on a cached request raise INVALID_ARGUMENT upfront. - Timeouts: on the Gemini API, X-Server-Timeout is floored at 10s while httpx keeps the shorter local deadline. Interactions drop the synthetic floor header. Case-variant custom headers replace instead of concatenating. - Request building skips parts with no Gemini field (Part.data), and dict config reads camelCase api_version/base_url/location. --- packages/genkit-google-genai/README.md | 5 +- .../src/genkit_google_genai/_google.py | 35 ++- .../_interactions/_client.py | 7 +- .../_models/_context_caching/_constants.py | 14 +- .../_models/_context_caching/_utils.py | 75 ++++- .../genkit_google_genai/_models/_gemini.py | 55 ++-- .../_models/_sdk_config.py | 17 ++ .../src/genkit_google_genai/_models/_utils.py | 270 ++++++++++++++---- .../tests/gemini_media_download_test.py | 236 ++++++++++++++- .../tests/gemini_server_timeout_floor_test.py | 158 ++++++++++ .../tests/gemini_tool_config_test.py | 191 +++++++++++++ .../tests/models/context_cache_test.py | 144 ++++++++++ .../tests/part_converter_fidelity_test.py | 22 ++ .../tests/part_converter_test.py | 57 +++- .../tests/vertexai_project_test.py | 2 +- 15 files changed, 1178 insertions(+), 110 deletions(-) create mode 100644 packages/genkit-google-genai/tests/gemini_server_timeout_floor_test.py create mode 100644 packages/genkit-google-genai/tests/gemini_tool_config_test.py create mode 100644 packages/genkit-google-genai/tests/models/context_cache_test.py diff --git a/packages/genkit-google-genai/README.md b/packages/genkit-google-genai/README.md index 7d837cb1c..4be91102e 100644 --- a/packages/genkit-google-genai/README.md +++ b/packages/genkit-google-genai/README.md @@ -203,8 +203,9 @@ Setting any `google_search_*` option turns Google Search on; `timeout` sets the HTTP timeout for one request, in seconds: `GeminiConfig(timeout=30)`. 0, negative, inf, NaN and bool raise. On `GoogleAI`, -the Gemini API rejects server deadlines under 10 seconds with HTTP 400 -(`VertexAI` accepts shorter values). +the Gemini API rejects server deadlines under 10 seconds, so a shorter timeout +sends `X-Server-Timeout: 10` and the shorter deadline is enforced locally +(`VertexAI` sends the value as-is). Function calling mode is controlled by `ai.generate(tool_choice=...)`, not config: `'auto'`, `'required'`, or `'none'`. In `'required'` mode, Gemini binds the request's 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..eaa4332eb 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -143,6 +143,7 @@ strip_ref_prefixes, ) from genkit_google_genai._models._sdk_config import ( + GEMINI_API_MIN_SERVER_TIMEOUT_SECONDS, check_timeout_seconds, request_client_kwargs, timeout_seconds_to_ms, @@ -742,6 +743,7 @@ def __init__( if not api_key and credentials is None: _setup_logger.warning(MISSING_API_KEY_MESSAGE) + self._caller_server_timeout = any(k.lower() == 'x-server-timeout' for k in (headers or ())) self._client_kwargs: dict[str, Any] = { 'vertexai': self._vertexai, 'api_key': api_key, @@ -752,6 +754,7 @@ def __init__( headers=headers, timeout=timeout, max_retries=max_retries, + min_server_timeout=GEMINI_API_MIN_SERVER_TIMEOUT_SECONDS, ), } self._http_client_factory = _loop_local_http_client(http_client_factory) @@ -776,13 +779,24 @@ def _interactions_client_options(self) -> ClientOptions: """Plugin-level transport knobs for Interactions models. Per-request config can still override timeout/headers/api_version. - A ticket never supplies the host. + A ticket never supplies the host. A synthetic ``X-Server-Timeout`` floor + added for short ``generate_content`` calls is omitted here so long + Interactions runs (Deep Research, Antigravity) are not cut off at 10s. """ http_options: HttpOptions = self._client_kwargs['http_options'] + custom_headers = ( + { + k: v + for k, v in http_options.headers.items() + if self._caller_server_timeout or k.lower() != 'x-server-timeout' + } + if http_options.headers + else None + ) return ClientOptions( api_version=http_options.api_version, base_url=http_options.base_url, - custom_headers=dict(http_options.headers) if http_options.headers else None, + custom_headers=custom_headers or None, timeout=float(http_options.timeout) if http_options.timeout is not None else None, # The getter, not a client: Interactions calls it per request so # each event loop gets its own client. @@ -1560,6 +1574,7 @@ def _plugin_http_options( headers: Mapping[str, str] | None = None, timeout: float | None = None, max_retries: int | None = None, + min_server_timeout: int | None = None, ) -> HttpOptions: """Build the SDK's HttpOptions from the plugin's network arguments. @@ -1575,6 +1590,11 @@ def _plugin_http_options( ``max_retries`` follows the OpenAI and Anthropic SDKs (retries after the first attempt) and maps onto ``HttpRetryOptions.attempts``, which counts the first attempt. google-genai's backoff and status codes are kept. + + ``min_server_timeout`` is the smallest ``X-Server-Timeout`` the backend + accepts. google-genai derives that header from ``timeout``; below the + floor the header is pinned to the floor and the local deadline stays + ``timeout``. """ checked_timeout = check_timeout_seconds(timeout) if max_retries is not None and ( @@ -1594,6 +1614,17 @@ def _plugin_http_options( else: merged[name] = caller + caller_server_timeout: str | None = None + for k in list(merged): + if k.lower() == 'x-server-timeout': + caller_server_timeout = merged.pop(k) + if caller_server_timeout is not None: + # google-genai checks exact case 'X-Server-Timeout' before adding its + # own derived header, so normalize any caller spelling here. + merged['X-Server-Timeout'] = caller_server_timeout + elif checked_timeout is not None and min_server_timeout is not None and checked_timeout < min_server_timeout: + merged['X-Server-Timeout'] = str(min_server_timeout) + return HttpOptions( base_url=base_url or None, api_version=api_version or None, diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_client.py b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_client.py index 9a0be79c7..ae6bbb60a 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_client.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_client.py @@ -60,9 +60,12 @@ def headers(*, api_key: str, client_options: ClientOptions | None) -> dict[str, """Build request headers; api key and Genkit client attribution win over custom. Header names are matched case-insensitively so ``X-Goog-Api-Key`` cannot - sneak a second key onto the request. + sneak a second key onto the request, and case-variant custom headers replace + rather than concatenate. """ - custom = httpx.Headers((client_options or ClientOptions()).custom_headers or {}) + custom = httpx.Headers() + for name, value in ((client_options or ClientOptions()).custom_headers or {}).items(): + custom[name] = value for name in RESERVED_HEADERS: custom.pop(name, None) custom['Content-Type'] = 'application/json' diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_context_caching/_constants.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_context_caching/_constants.py index b7c5a2028..d33bcd412 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_context_caching/_constants.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_context_caching/_constants.py @@ -17,18 +17,10 @@ """Constants for context caching.""" -CONTEXT_CACHE_SUPPORTED_MODELS = [ - 'gemini-2.0-flash', - 'gemini-2.0-flash-001', - 'gemini-3-flash-preview', -] - +# No model allowlist: the set of cache-capable models changes with every +# release, and the API rejects a model that can't cache with a clear error. INVALID_ARGUMENT_MESSAGES = { - 'modelVersion': ( - 'Model version is required for context caching. Supported models: ' - + ', '.join(CONTEXT_CACHE_SUPPORTED_MODELS) - + '.' - ), + 'modelVersion': 'Model version is required for context caching.', 'tools': 'Context caching cannot be used simultaneously with tools.', 'codeExecution': 'Context caching cannot be used simultaneously with code execution.', } diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_context_caching/_utils.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_context_caching/_utils.py index 9dc6f5234..1d383b72b 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_context_caching/_utils.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_context_caching/_utils.py @@ -18,11 +18,10 @@ import hashlib import json +from collections.abc import Mapping +from typing import Any, cast -from genkit_google_genai._models._context_caching._constants import ( - CONTEXT_CACHE_SUPPORTED_MODELS, - INVALID_ARGUMENT_MESSAGES, -) +from genkit_google_genai._models._context_caching._constants import INVALID_ARGUMENT_MESSAGES from google.genai import types as genai_types from genkit import GenkitError, get_logger @@ -52,6 +51,32 @@ def generate_cache_key(contents: list[genai_types.Content], model_name: str) -> return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() +def _config_flag(config: object, snake: str, camel: str) -> Any: # noqa: ANN401 + if isinstance(config, Mapping): + mapping = cast(Mapping[str, Any], config) + if snake in mapping: + return mapping[snake] + if camel in mapping: + return mapping[camel] + return None + return getattr(config, snake, None) + + +def _has_nonempty_items(value: object) -> bool: + if not isinstance(value, list): + return bool(value) + return any(bool(item) for item in cast(list[object], value)) + + +_GOOGLE_SEARCH_OPTION_PAIRS: tuple[tuple[str, str], ...] = ( + ('google_search_types', 'googleSearchTypes'), + ('google_search_exclude_domains', 'googleSearchExcludeDomains'), + ('google_search_blocking_confidence', 'googleSearchBlockingConfidence'), + ('google_search_start_time', 'googleSearchStartTime'), + ('google_search_end_time', 'googleSearchEndTime'), +) + + def validate_context_cache_request(request: ModelRequest, model_name: str) -> bool: """Verifies that the context cache request could be processed for the request. @@ -60,9 +85,9 @@ def validate_context_cache_request(request: ModelRequest, model_name: str) -> bo model_name: Name of the generation model to check Returns: - True if the context cache request could be processed for the request, False otherwise + True if the context cache request could be processed for the request """ - if not model_name or model_name not in CONTEXT_CACHE_SUPPORTED_MODELS: + if not model_name: raise GenkitError( status='INVALID_ARGUMENT', message=INVALID_ARGUMENT_MESSAGES['modelVersion'], @@ -72,10 +97,36 @@ def validate_context_cache_request(request: ModelRequest, model_name: str) -> bo status='INVALID_ARGUMENT', message=INVALID_ARGUMENT_MESSAGES['tools'], ) - # TODO(#4360): add this check when code execution is added to Genkit - # if request.config and request.config.get("codeExecution"): - # raise GenkitError( - # status="INVALID_ARGUMENT", - # message=INVALID_ARGUMENT_MESSAGES["codeExecution"], - # ) + config = request.config + if _config_flag(config, 'code_execution', 'codeExecution'): + raise GenkitError( + status='INVALID_ARGUMENT', + message=INVALID_ARGUMENT_MESSAGES['codeExecution'], + ) + google_search = _config_flag(config, 'google_search', 'googleSearch') + has_search_options = google_search is not False and any( + _has_nonempty_items(val) + for snake, camel in _GOOGLE_SEARCH_OPTION_PAIRS + if (val := _config_flag(config, snake, camel)) is not None + ) + if google_search or has_search_options: + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'{INVALID_ARGUMENT_MESSAGES["tools"]} (google_search)', + ) + if _config_flag(config, 'url_context', 'urlContext'): + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'{INVALID_ARGUMENT_MESSAGES["tools"]} (url_context)', + ) + stores = _config_flag(config, 'file_search_store_names', 'fileSearchStoreNames') + has_file_search_opts = ( + _config_flag(config, 'file_search_metadata_filter', 'fileSearchMetadataFilter') is not None + or _config_flag(config, 'file_search_top_k', 'fileSearchTopK') is not None + ) + if _has_nonempty_items(stores) or has_file_search_opts: + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'{INVALID_ARGUMENT_MESSAGES["tools"]} (file_search_store_names)', + ) return True 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..6de813871 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 @@ -39,6 +39,7 @@ reject_bool_timeout, request_client_kwargs, sdk_config_error, + server_timeout_header, split_sdk_fields, timeout_seconds_to_ms, ) @@ -686,7 +687,8 @@ class GeminiConfig(ModelConfig): default=None, description=( 'HTTP timeout for this request, in seconds (positive, finite). Overrides the plugin timeout for this call. ' - 'The Gemini API rejects deadlines under 10s with HTTP 400; Vertex AI accepts shorter values.' + 'The Gemini API rejects server deadlines under 10s, so the plugin sends a 10s server deadline there ' + 'and enforces the shorter timeout locally.' ), ) @@ -733,7 +735,8 @@ def _check_timeout(cls, value: float | None) -> float | None: context_cache: bool | None = Field( default=None, description=( - 'Context caching allows you to save and reuse precomputed input tokens that you wish to use repeatedly.' + 'Context caching allows you to save and reuse precomputed input tokens that you wish to use repeatedly. ' + "Mark the last message to cache with metadata={'cache': True}. False ignores those markers." ), ) @@ -2182,14 +2185,9 @@ async def _resolve_request_client( raise missing_api_key_error() if request.config: - if isinstance(request.config, dict): - api_version = request.config.get('api_version') - base_url_override = request.config.get('base_url') - location_override = request.config.get('location') - else: - api_version = getattr(request.config, 'api_version', None) - base_url_override = getattr(request.config, 'base_url', None) - location_override = getattr(request.config, 'location', None) + api_version = _config_value(request.config, 'api_version', 'apiVersion') + base_url_override = _config_value(request.config, 'base_url', 'baseUrl') + location_override = _config_value(request.config, 'location') if location_override and not self._is_vertex(): # Location is a Vertex AI concept; ignore it for the Gemini API backend. @@ -2445,6 +2443,8 @@ async def _build_messages( """ request_contents: list[genai_types.Content] = [] cache = None + # context_cache=False turns off metadata['cache'] markers for this call. + use_cache = _config_value(request.config, 'context_cache', 'contextCache') is not False gemma = is_gemma_model(model_name) for msg in request.messages: @@ -2458,15 +2458,16 @@ async def _build_messages( continue p = stripped converted = await PartConverter.to_gemini(p, tools=tools) - if isinstance(converted, list): - content_parts.extend(converted) - else: - content_parts.append(converted) + for gemini_part in converted if isinstance(converted, list) else [converted]: + # A part Gemini has no field for (Part.data, say) converts + # to an empty Part(), which the API rejects. + if gemini_part.model_dump(exclude_none=True): + content_parts.append(gemini_part) role = 'model' if msg.role in (Role.MODEL, 'model') else 'user' if content_parts: request_contents.append(genai_types.Content(parts=content_parts, role=role)) - if msg.metadata and msg.metadata.get('cache'): + if use_cache and msg.metadata and msg.metadata.get('cache'): cache = await self._retrieve_cached_content( request=request, model_name=model_name, @@ -2623,10 +2624,22 @@ async def _genkit_to_googleai_cfg( if tools: cfg.tools = cast(genai_types.ToolListUnion, tools) + # Genkit runs tools itself. google-genai's AFC only runs Python + # callables and warns about every FunctionDeclaration. + cfg.automatic_function_calling = genai_types.AutomaticFunctionCallingConfig(disable=True) if tool_choice: cfg.tool_config = _tool_config(tool_choice, function_tools) + if self._needs_server_side_tool_invocations(tools): + # Gemini 3 rejects built-in tools (google_search, url_context, + # code_execution, file_search) next to function declarations + # unless the request opts in to server-side tool invocations. + # The Gemini API only; Vertex AI has no such field. + if cfg.tool_config is None: + cfg.tool_config = genai_types.ToolConfig() + cfg.tool_config.include_server_side_tool_invocations = True + cfg.system_instruction = genai_types.Content(parts=system_instruction) if system_instruction else None cfg = attach_leftovers(cfg, leftovers, nest='generationConfig') cfg = attach_config_extra( @@ -2648,7 +2661,9 @@ async def _genkit_to_googleai_cfg( headers = { key: val for key, val in (http_options.headers or {}).items() if key.lower() != 'x-server-timeout' } - headers['X-Server-Timeout'] = str(math.ceil(ms / 1000)) + # The Gemini API rejects X-Server-Timeout under 10s with a 400; + # the header is floored there and httpx still enforces `ms`. + headers['X-Server-Timeout'] = server_timeout_header(ms, vertexai=bool(self._client.vertexai)) http_options.headers = headers cfg.http_options = http_options return cfg @@ -2664,6 +2679,14 @@ async def _genkit_to_googleai_cfg( # Keys that may not be supported by older google-genai SDK versions. _SDK_GATED_KEYS = frozenset(['image_config', 'thinking_config', 'response_modalities']) + def _needs_server_side_tool_invocations(self, tools: list[genai_types.Tool]) -> bool: + """Whether *tools* mixes function declarations with built-in tools on the Gemini API.""" + if self._client.vertexai: + return False + has_functions = any(tool.function_declarations for tool in tools) + has_builtin = any(not tool.function_declarations for tool in tools) + return has_functions and has_builtin + def _apply_output_config(self, cfg: genai_types.GenerateContentConfig, request: ModelRequest) -> None: """Set the response MIME type and schema for the request's output format. 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..ace17485e 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 @@ -288,6 +288,23 @@ def check_timeout_seconds(value: object) -> float | None: return float(value) +# The Gemini API answers 400 to an X-Server-Timeout under 10 seconds instead +# of timing out. Vertex AI accepts shorter deadlines. +GEMINI_API_MIN_SERVER_TIMEOUT_SECONDS = 10 + + +def server_timeout_header(timeout_ms: int, *, vertexai: bool) -> str: + """``X-Server-Timeout`` for a request whose local deadline is *timeout_ms*. + + On the Gemini API the header never goes under the API's 10 second floor; + the local httpx deadline still fires at *timeout_ms*. + """ + seconds = math.ceil(timeout_ms / 1000) + if not vertexai: + seconds = max(seconds, GEMINI_API_MIN_SERVER_TIMEOUT_SECONDS) + return str(seconds) + + def reject_bool_timeout(value: object) -> object: """Before-validator: pydantic turns ``True`` into ``1.0`` before an after-validator sees it.""" if isinstance(value, bool): 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..5d0a828a6 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 @@ -49,13 +49,16 @@ import base64 import binascii +import re +import zlib from collections.abc import Sequence from dataclasses import dataclass from typing import Any, cast -from urllib.parse import urlparse, urlsplit, urlunsplit +from urllib.parse import unquote_to_bytes, urlparse, urlsplit, urlunsplit import httpx from google import genai +from pydantic import ValidationError from genkit import GenkitError, Part, get_logger from genkit.model import ToolRequest, ToolResponse @@ -161,6 +164,9 @@ class PartConverter: EXECUTABLE_CODE = 'executableCode' CODE_EXECUTION_RESULT = 'codeExecutionResult' + # Server-side (built-in) tool invocations, as in the JS plugin. + GEMINI_TOOL_CALL = 'geminiToolCall' + GEMINI_TOOL_RESPONSE = 'geminiToolResponse' OUTCOME = 'outcome' OUTPUT = 'output' LANGUAGE = 'language' @@ -245,6 +251,8 @@ async def to_gemini( media = _function_response_part(gemini_part) if media is not None: fn_media.append(media) + except (GenkitError, httpx.HTTPError): + raise except Exception as exc: logger.debug('Skipping unrecognised tool-response content part: %s', exc) @@ -262,13 +270,12 @@ async def to_gemini( media_info = item['media'] url = media_info.get('url') or '' content_type = media_info.get('contentType') or media_info.get('content_type') - if url.startswith(cls.DATA): - _, data_str = url.split(',', 1) - data = base64.b64decode(data_str) + if url.lower().startswith(cls.DATA): + uri_mime, data = _decode_data_uri(url) fn_media.append( genai.types.FunctionResponsePart.from_bytes( data=data, - mime_type=content_type or 'application/octet-stream', + mime_type=_media_type(content_type) or uri_mime or 'application/octet-stream', ) ) if fn_media: @@ -291,21 +298,17 @@ async def to_gemini( ) if part.media is not None: url = part.media.url - if url.startswith(cls.DATA): - # Extract mime type and data from data:mime_type;base64,data - metadata, data_str = url.split(',', 1) - mime_type = part.media.content_type or metadata.split(':', 1)[1].split(';', 1)[0] - data = base64.b64decode(data_str) - + if url.lower().startswith(cls.DATA): + uri_mime, data = _decode_data_uri(url) return genai.types.Part( inline_data=genai.types.Blob( - mime_type=mime_type, + mime_type=_media_type(part.media.content_type) or uri_mime or 'application/octet-stream', data=data, ), thought_signature=signature, ) - if url.startswith('http'): + if url.lower().startswith(('http://', 'https://')): # URLs from hosts the Gemini API can natively resolve (YouTube, # Files API) are passed as file_data — downloading them would # fetch HTML pages instead of actual media content. @@ -322,8 +325,12 @@ async def to_gemini( # middleware (JS parity) once model middleware is implemented. # The Gemini API cannot fetch arbitrary HTTP URLs via file_uri, # so we must download the content and send it as inline_data. - data, mime_type = await cls._download_image(url) - mime_type = mime_type or part.media.content_type or 'image/jpeg' + data, served_type = await cls._download_image(url) + # The caller's content_type wins: object stores (S3, R2, GCS) + # often serve application/octet-stream, which Gemini rejects. + mime_type = ( + _media_type(part.media.content_type) or _media_type(served_type, skip_generic=True) or 'image/jpeg' + ) return genai.types.Part( inline_data=genai.types.Blob( mime_type=mime_type, @@ -334,6 +341,9 @@ async def to_gemini( # Non-HTTP, non-data URIs (e.g. gs://, Files API URIs) are # passed through as file_data — the Gemini API can resolve these. + # Local paths and raw base64 are not URIs; refuse them here rather + # than send them to Gemini and get them echoed back in a 400. + _reject_non_uri_media(url) return genai.types.Part( file_data=genai.types.FileData( mime_type=part.media.content_type, @@ -379,6 +389,32 @@ def _to_gemini_custom(cls, part: Part) -> genai.types.Part: ), thought_signature=signature, ) + if part.custom and cls.GEMINI_TOOL_CALL in part.custom: + try: + tool_call = genai.types.ToolCall.model_validate(part.custom[cls.GEMINI_TOOL_CALL]) + except (ValidationError, TypeError, ValueError) as e: + raise GenkitError( + status='INVALID_ARGUMENT', + message='Invalid custom.geminiToolCall payload', + cause=e, + ) from e + return genai.types.Part( + tool_call=tool_call, + thought_signature=signature, + ) + if part.custom and cls.GEMINI_TOOL_RESPONSE in part.custom: + try: + tool_response = genai.types.ToolResponse.model_validate(part.custom[cls.GEMINI_TOOL_RESPONSE]) + except (ValidationError, TypeError, ValueError) as e: + raise GenkitError( + status='INVALID_ARGUMENT', + message='Invalid custom.geminiToolResponse payload', + cause=e, + ) from e + return genai.types.Part( + tool_response=tool_response, + thought_signature=signature, + ) return genai.types.Part() @classmethod @@ -477,6 +513,22 @@ def from_gemini(cls, part: genai.types.Part, *, tools: ToolTable | None = None) }, metadata=signature, ) + if part.tool_call: + # A built-in tool the server ran (include_server_side_tool_invocations). + # Kept wire-shaped so the next turn can send it back unchanged. + return Part( + custom={cls.GEMINI_TOOL_CALL: part.tool_call.model_dump(mode='json', by_alias=True, exclude_none=True)}, + metadata=cls._encode_thought_signature(part.thought_signature), + ) + if part.tool_response: + return Part( + custom={ + cls.GEMINI_TOOL_RESPONSE: part.tool_response.model_dump( + mode='json', by_alias=True, exclude_none=True + ) + }, + metadata=cls._encode_thought_signature(part.thought_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 @@ -543,9 +595,11 @@ async def _download_image(cls, url: str) -> tuple[bytes, str | None]: A tuple containing the content (bytes) and its MIME type (str or None). Raises: - GenkitError: INVALID_ARGUMENT if the body is larger than 20MB, - if the host sends a compressed ``Content-Encoding``, or when - the media host answers with a 4xx other than 408/429. + GenkitError: INVALID_ARGUMENT if the body is larger than 20MB + (after gzip/deflate decoding), if the compressed body is + corrupt or truncated, if the host sends any other + ``Content-Encoding`` (br, zstd), or when the media host + answers with a 4xx other than 408/429. httpx.HTTPStatusError: A 5xx, 408, or 429 from the media host, left raw. It is not Gemini's failure, so Fallback must not switch models over it (the next model needs the same URL); Retry @@ -554,43 +608,81 @@ async def _download_image(cls, url: str) -> tuple[bytes, str | None]: unclassified because it may pass on retry. """ client = _media_client() - async with client.stream('GET', url, timeout=60.0) as response: - try: - response.raise_for_status() - except httpx.HTTPStatusError as e: - code = e.response.status_code - where = _redact_url(str(e.request.url)) - sanitized = httpx.HTTPStatusError( - f'HTTP {code} for {where}', - request=e.request, - response=e.response, - ) - if 400 <= code < 500 and code not in (408, 429): + try: + async with client.stream('GET', url, timeout=60.0) as response: + try: + response.raise_for_status() + except httpx.HTTPStatusError as e: + code = e.response.status_code + where = _redact_url(str(e.request.url)) + sanitized = httpx.HTTPStatusError( + f'HTTP {code} for {where}', + request=e.request, + response=e.response, + ) + if 400 <= code < 500 and code not in (408, 429): + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'Could not download request media (HTTP {code} for {where})', + cause=sanitized, + ) from sanitized + raise sanitized from None + encoding = response.headers.get('content-encoding', '').strip().lower() + if encoding not in ('', 'identity', 'gzip', 'x-gzip', 'deflate'): raise GenkitError( status='INVALID_ARGUMENT', - message=f'Could not download request media (HTTP {code} for {where})', - cause=sanitized, - ) from sanitized - raise sanitized from None - encoding = response.headers.get('content-encoding', '').strip().lower() - if encoding not in ('', 'identity'): - raise GenkitError( - status='INVALID_ARGUMENT', - message=( - f'media at {_redact_url(url)} sent unsupported ' - f'Content-Encoding {encoding!r}; expected uncompressed bytes' - ), - ) - declared = response.headers.get('content-length', '') - if declared.isdigit() and int(declared) > _MAX_MEDIA_DOWNLOAD_BYTES: - raise _media_too_large(url) - body = bytearray() - chunks = response.aiter_bytes() if response.is_stream_consumed else response.aiter_raw() - async for chunk in chunks: - body.extend(chunk) - if len(body) > _MAX_MEDIA_DOWNLOAD_BYTES: + message=( + f'media at {_redact_url(url)} sent unsupported ' + f'Content-Encoding {encoding!r}; expected identity, gzip or deflate' + ), + ) + declared = response.headers.get('content-length', '') + if declared.isdigit() and int(declared) > _MAX_MEDIA_DOWNLOAD_BYTES: raise _media_too_large(url) - return bytes(body), response.headers.get('content-type') + # Some CDNs gzip despite Accept-Encoding: identity. Decompress here, + # bounded, so the cap applies to the decompressed size and a small + # compressed body can't expand past it in one step. + decoder = _bounded_decoder(encoding) + chunks = response.aiter_raw() + if response.is_stream_consumed: + # Already read (mock transports): httpx has decoded it. + decoder, chunks = None, response.aiter_bytes() + body = bytearray() + try: + async for chunk in chunks: + if decoder is None: + body.extend(chunk) + else: + data = chunk + while data: + body.extend(decoder.decompress(data, _MAX_MEDIA_DOWNLOAD_BYTES + 1 - len(body))) + if len(body) > _MAX_MEDIA_DOWNLOAD_BYTES: + raise _media_too_large(url) + data = decoder.unconsumed_tail + if len(body) > _MAX_MEDIA_DOWNLOAD_BYTES: + raise _media_too_large(url) + if decoder is not None: + body.extend(decoder.flush()) + if len(body) > _MAX_MEDIA_DOWNLOAD_BYTES: + raise _media_too_large(url) + except zlib.error as e: + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'media at {_redact_url(url)} has a corrupt {encoding} body', + cause=e, + ) from e + if decoder is not None and not decoder.eof: + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'media at {_redact_url(url)} has a truncated {encoding} body', + ) + return bytes(body), response.headers.get('content-type') + except httpx.DecodingError as e: + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'media at {_redact_url(url)} has a corrupt compressed body', + cause=e, + ) from e # A truncated image or video is a corrupt file, so a URL over the cap fails @@ -611,3 +703,77 @@ def _enum_value(value: object) -> object: def _media_too_large(url: str) -> GenkitError: return GenkitError(status='INVALID_ARGUMENT', message=f'media at {_redact_url(url)} is larger than 20MB') + + +def _bounded_decoder(encoding: str) -> Any: # noqa: ANN401 + """A zlib decompressobj for a gzip/deflate Content-Encoding, or None for identity.""" + if encoding in ('gzip', 'x-gzip'): + return zlib.decompressobj(16 + zlib.MAX_WBITS) + if encoding == 'deflate': + # RFC 9110 deflate is zlib-wrapped; 32 + MAX_WBITS also accepts gzip headers. + return zlib.decompressobj(32 + zlib.MAX_WBITS) + return None + + +# Media types that say nothing about the content; a caller's or the URI's type is better. +_GENERIC_MEDIA_TYPES = frozenset({'application/octet-stream', 'binary/octet-stream', 'application/x-binary'}) + + +def _media_type(value: str | None, *, skip_generic: bool = False) -> str | None: + """*value* without parameters (``; charset=...``), lowercased; None if empty or generic when *skip_generic*.""" + if not value: + return None + media_type = value.split(';', 1)[0].strip().lower() + if not media_type or (skip_generic and media_type in _GENERIC_MEDIA_TYPES): + return None + return media_type + + +def _invalid_media(message: str) -> GenkitError: + return GenkitError(status='INVALID_ARGUMENT', message=message) + + +def _decode_data_uri(url: str) -> tuple[str | None, bytes]: + """The media type and bytes of an RFC 2397 ``data:`` URI. + + Raises: + GenkitError: INVALID_ARGUMENT for a URI with no ``,`` or a payload + that doesn't decode. The payload is not echoed back. + """ + header, sep, payload = url.partition(',') + if not sep: + raise _invalid_media("media data: URI has no ',' before its payload; expected data:;base64,") + params = header[len('data:') :].split(';') + is_base64 = any(p.strip().lower() == 'base64' for p in params[1:]) + try: + data = ( + base64.b64decode(payload.translate(_ASCII_WHITESPACE), validate=True) + if is_base64 + else unquote_to_bytes(payload) + ) + except (binascii.Error, ValueError) as e: + raise _invalid_media('media data: URI payload is not valid base64') from e + return _media_type(params[0]), data + + +# A Windows drive path (C:\x or C:/x) parses as a one-letter URI scheme. +_WINDOWS_PATH = re.compile(r'^[A-Za-z]:[\\/]') + + +def _reject_non_uri_media(url: str) -> None: + """Raise for media URLs Gemini can't resolve: ``file://``, local paths, schemeless strings. + + The message names the problem, not the value, so a path or payload + isn't echoed into logs and traces. + """ + scheme = urlsplit(url).scheme.lower() if not _WINDOWS_PATH.match(url) else '' + if scheme == 'file' or (not scheme and (url.startswith(('/', './', '../', '~', '\\')) or _WINDOWS_PATH.match(url))): + raise _invalid_media( + 'media url is a local file path; Gemini cannot read local files. ' + 'Read the bytes and pass a data: URI, or upload the file and pass its URI.' + ) + if not scheme: + raise _invalid_media( + 'media url has no URI scheme; pass inline bytes as a data:;base64, URI, ' + 'or pass an https:// or gs:// URI.' + ) diff --git a/packages/genkit-google-genai/tests/gemini_media_download_test.py b/packages/genkit-google-genai/tests/gemini_media_download_test.py index 15942b44f..23d49b6fe 100644 --- a/packages/genkit-google-genai/tests/gemini_media_download_test.py +++ b/packages/genkit-google-genai/tests/gemini_media_download_test.py @@ -18,6 +18,7 @@ import base64 import gzip +import zlib from collections.abc import AsyncIterator, Callable, Iterator from contextlib import contextmanager from pathlib import Path @@ -317,31 +318,76 @@ async def test_generate_gemini_youtube_url_is_sent_as_file_uri(gemini: tuple[Gen @pytest.mark.asyncio -async def test_generate_gemini_local_file_path_media_is_not_opened( +async def test_generate_gemini_local_file_path_media_is_rejected_unread( gemini: tuple[Genkit, MagicMock], tmp_path: Path ) -> None: - """A path to a real file on the server is passed as a file URI; its bytes are never read or sent.""" + """A local path or file:// URI is INVALID_ARGUMENT; the file is never read and the path isn't echoed.""" ai, sdk = gemini secret = tmp_path / 'cat.png' secret.write_bytes(b'server-side secret') - for url in (str(secret), secret.as_uri()): + for url in (str(secret), secret.as_uri(), './cat.png', '~/cat.png', 'C:\\Users\\chef\\cat.png'): with _no_download(): response = await _describe(ai, url) - assert response.finish_reason == FinishReason.STOP - assert response.text == 'ok' - sent = _sent_media(sdk) - assert sent.inline_data is None - assert sent.file_data is not None - assert sent.file_data.file_uri == url + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + assert response.finish_message is not None + assert 'local file path' in response.finish_message + assert 'cat.png' not in response.finish_message + sdk.aio.models.generate_content.assert_not_called() + + +@pytest.mark.asyncio +async def test_generate_gemini_raw_base64_media_is_rejected(gemini: tuple[Genkit, MagicMock]) -> None: + """Raw base64 passed as a URL is INVALID_ARGUMENT pointing at data: URIs, without echoing the payload.""" + ai, sdk = gemini + payload = base64.b64encode(PNG * 40).decode() + + response = await _describe(ai, payload) + + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + assert response.finish_message is not None + assert 'data:' in response.finish_message + assert payload[:40] not in response.finish_message + sdk.aio.models.generate_content.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize('url', ['data:image/png;base64', 'data:image/png;base64,%%%not-base64']) +async def test_generate_gemini_malformed_data_uri_is_invalid_argument( + gemini: tuple[Genkit, MagicMock], url: str +) -> None: + """A data: URI with no comma or a payload that doesn't decode is INVALID_ARGUMENT, not a raw ValueError.""" + ai, sdk = gemini + + response = await _describe(ai, url) + + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + sdk.aio.models.generate_content.assert_not_called() + + +@pytest.mark.asyncio +async def test_generate_gemini_percent_encoded_data_uri_is_decoded(gemini: tuple[Genkit, MagicMock]) -> None: + """A data: URI without ;base64 carries percent-encoded bytes (RFC 2397).""" + ai, sdk = gemini + + await _describe(ai, 'data:text/plain,Pesto%20contains%20pine%20nuts', 'text/plain') + + sent = _sent_media(sdk) + assert sent.inline_data is not None + assert sent.inline_data.data == b'Pesto contains pine nuts' + assert sent.inline_data.mime_type == 'text/plain' @pytest.mark.asyncio -async def test_generate_gemini_http_media_rejects_gzip_content_encoding_without_decompressing( +async def test_generate_gemini_http_media_gzip_over_cap_after_decompressing_is_rejected( gemini: tuple[Genkit, MagicMock], ) -> None: - """`_media_client` sends `Accept-Encoding: identity` and rejects gzip responses before decompressing.""" + """`_media_client` asks for identity; a gzip body that expands past 20MB is rejected at the cap.""" ai, sdk = gemini seen_headers: list[dict[str, str]] = [] @@ -405,3 +451,171 @@ async def test_generate_gemini_http_media_status_errors_omit_query_string_and_us assert 's3cr3t' not in text assert 'pw' not in text sdk.aio.models.generate_content.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize('served', ['application/octet-stream', 'binary/octet-stream', 'image/jpeg']) +async def test_generate_gemini_http_media_caller_content_type_wins( + gemini: tuple[Genkit, MagicMock], served: str +) -> None: + """An explicit content_type beats the host's header; S3/R2 serve application/octet-stream.""" + ai, sdk = gemini + + with _serve(lambda request: httpx.Response(200, headers={'content-type': served}, content=PNG)): + response = await _describe(ai, 'https://bucket.r2.example/menu.png', 'image/png') + + assert response.finish_reason == FinishReason.STOP + sent = _sent_media(sdk) + assert sent.inline_data is not None + assert sent.inline_data.mime_type == 'image/png' + + +@pytest.mark.asyncio +async def test_generate_gemini_http_media_without_caller_type_skips_generic_header( + gemini: tuple[Genkit, MagicMock], +) -> None: + """With no caller type, a specific served type is used with its parameters stripped; octet-stream is not.""" + ai, sdk = gemini + + with _serve( + lambda request: httpx.Response(200, headers={'content-type': 'image/webp; charset=binary'}, content=PNG) + ): + await ai.generate( + model='googleai/gemini-2.5-flash', + messages=[Message(role=Role.USER, content=[Part.from_media(url='https://cdn.example/a.webp')])], + ) + sent = _sent_media(sdk) + assert sent.inline_data is not None + assert sent.inline_data.mime_type == 'image/webp' + + with _serve(lambda request: httpx.Response(200, headers={'content-type': 'application/octet-stream'}, content=PNG)): + await ai.generate( + model='googleai/gemini-2.5-flash', + messages=[Message(role=Role.USER, content=[Part.from_media(url='https://cdn.example/a')])], + ) + sent = _sent_media(sdk) + assert sent.inline_data is not None + assert sent.inline_data.mime_type == 'image/jpeg' + + +@pytest.mark.asyncio +@pytest.mark.parametrize('encoding', ['gzip', 'deflate']) +async def test_generate_gemini_http_media_compressed_under_cap_is_decompressed( + gemini: tuple[Genkit, MagicMock], encoding: str +) -> None: + """A CDN that compresses anyway: the decompressed bytes are what Gemini receives.""" + ai, sdk = gemini + body = gzip.compress(PNG) if encoding == 'gzip' else zlib.compress(PNG) + + with _serve( + lambda request: httpx.Response( + 200, headers={'content-type': 'image/png', 'content-encoding': encoding}, content=body + ) + ): + response = await _describe(ai, 'https://cdn.example/menu.png') + + assert response.finish_reason == FinishReason.STOP + sent = _sent_media(sdk) + assert sent.inline_data is not None + assert sent.inline_data.data == PNG + + +@pytest.mark.asyncio +async def test_generate_gemini_http_media_unsupported_encoding_is_rejected(gemini: tuple[Genkit, MagicMock]) -> None: + """Encodings the plugin can't bound (br, zstd) stay INVALID_ARGUMENT.""" + ai, sdk = gemini + + with _serve( + lambda request: httpx.Response( + 200, headers={'content-type': 'image/png', 'content-encoding': 'br'}, content=PNG + ) + ): + response = await _describe(ai, 'https://cdn.example/menu.png') + + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + assert response.finish_message is not None + assert "'br'" in response.finish_message + sdk.aio.models.generate_content.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('encoding', 'raw'), + [ + ('gzip', b'not-a-gzip-stream'), + ('gzip', gzip.compress(PNG)[:-4]), + ('deflate', zlib.compress(PNG)[:-2]), + ], + ids=['corrupt-gzip', 'truncated-gzip', 'truncated-deflate'], +) +async def test_generate_gemini_http_media_corrupt_or_truncated_compression_is_invalid_argument( + gemini: tuple[Genkit, MagicMock], encoding: str, raw: bytes +) -> None: + """Corrupt or truncated compressed payloads fail with INVALID_ARGUMENT so Retry does not retry them.""" + ai, sdk = gemini + + with _serve( + lambda request: httpx.Response( + 200, + headers={'content-type': 'image/png', 'content-encoding': encoding}, + stream=httpx.ByteStream(raw), + ) + ): + response = await _describe(ai, 'https://cdn.example/menu.png?X-Goog-Signature=s3cr3t') + + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + assert response.finish_message is not None + assert 's3cr3t' not in response.finish_message + sdk.aio.models.generate_content.assert_not_called() + + +@pytest.mark.asyncio +async def test_generate_gemini_data_uri_strips_ascii_whitespace_and_validates_strictly( + gemini: tuple[Genkit, MagicMock], +) -> None: + """Wrapped valid base64 decodes; non-alphabet garbage that validate=False ignored raises INVALID_ARGUMENT.""" + ai, sdk = gemini + + with _no_download(): + ok = await _describe(ai, 'data:text/plain;base64,YWJj\n ZGVm\t', 'text/plain') + bad = await _describe(ai, 'data:image/png;base64,YWJj%%%!') + + assert ok.finish_reason == FinishReason.STOP + sent = _sent_media(sdk) + assert sent.inline_data is not None and sent.inline_data.data == b'abcdef' + assert bad.error is not None + assert bad.error.status == 'INVALID_ARGUMENT' + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'url', + [ + 'menu.png', + 'kitchen/menu.png', + 'http_menu.png', + '\\\\server\\share\\secret-menu.png', + base64.b64encode(b'short-inline-secret').decode(), + ], + ids=['bare-name', 'relative-subpath', 'http-prefix-no-scheme', 'unc-path', 'short-raw-base64'], +) +async def test_generate_gemini_schemeless_and_unc_media_urls_are_rejected_without_echo( + gemini: tuple[Genkit, MagicMock], url: str +) -> None: + """Any schemeless file_data URL or UNC path fails with INVALID_ARGUMENT and never echoes the value.""" + ai, sdk = gemini + + with _no_download(): + response = await _describe(ai, url) + + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + assert response.finish_message is not None + assert url not in response.finish_message + assert 'menu.png' not in response.finish_message + assert 'secret' not in response.finish_message + sdk.aio.models.generate_content.assert_not_called() diff --git a/packages/genkit-google-genai/tests/gemini_server_timeout_floor_test.py b/packages/genkit-google-genai/tests/gemini_server_timeout_floor_test.py new file mode 100644 index 000000000..3eb3ee10a --- /dev/null +++ b/packages/genkit-google-genai/tests/gemini_server_timeout_floor_test.py @@ -0,0 +1,158 @@ +# 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 + +"""Timeouts under 10s: the Gemini API rejects X-Server-Timeout below 10 with a 400.""" + +import json +from unittest.mock import MagicMock + +import httpx +import pytest +from genkit_google_genai import AntigravityConfig, DeepResearchConfig, GeminiConfig, GoogleAI +from genkit_google_genai._google import _plugin_http_options +from genkit_google_genai._models._gemini import GeminiModel +from google import genai + +from genkit import Genkit, Message, Part, Role +from genkit.model import ModelRequest + + +def _model(vertexai: bool) -> GeminiModel: + client = MagicMock(spec=genai.Client) + client.vertexai = vertexai + return GeminiModel('gemini-flash-latest', client) + + +def _request(timeout: float) -> ModelRequest: + return ModelRequest( + messages=[Message(role=Role.USER, content=[Part.from_text('Suggest a dish.')])], + config=GeminiConfig(timeout=timeout), + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('vertexai', 'timeout', 'header', 'ms'), + [ + (False, 5, '10', 5000), + (False, 0.25, '10', 250), + (False, 30, '30', 30000), + (True, 5, '5', 5000), + ], + ids=['googleai-5s', 'googleai-250ms', 'googleai-30s', 'vertex-5s'], +) +async def test_request_timeout_floors_server_header_on_gemini_api( + vertexai: bool, timeout: float, header: str, ms: int +) -> None: + """GeminiConfig(timeout=5) keeps a 5s local deadline but sends X-Server-Timeout: 10 to the Gemini API.""" + cfg = await _model(vertexai)._genkit_to_googleai_cfg(_request(timeout)) + + assert cfg is not None and cfg.http_options is not None + assert cfg.http_options.timeout == ms + assert cfg.http_options.headers is not None + assert cfg.http_options.headers['X-Server-Timeout'] == header + + +@pytest.mark.parametrize(('timeout', 'header'), [(3, '10'), (10, None), (60, None)]) +def test_plugin_timeout_floors_server_header(timeout: float, header: str | None) -> None: + """GoogleAI(timeout=3) pins X-Server-Timeout to 10; google-genai would otherwise derive 3.""" + opts = _plugin_http_options(timeout=timeout, min_server_timeout=10) + + assert opts.timeout == timeout * 1000 + assert (opts.headers or {}).get('X-Server-Timeout') == header + + +def test_plugin_timeout_without_floor_sets_no_header() -> None: + """VertexAI passes no floor; google-genai derives the header from timeout as before.""" + opts = _plugin_http_options(timeout=3) + + assert 'X-Server-Timeout' not in (opts.headers or {}) + + +@pytest.mark.asyncio +async def test_short_plugin_timeout_floor_does_not_leak_into_interactions_models() -> None: + """GoogleAI(timeout=5) + DeepResearchConfig(timeout=300) omits synthetic X-Server-Timeout: 10.""" + captured: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured.append(request) + if '/interactions' in request.url.path: + return httpx.Response( + 200, + json={ + 'id': 'int-1', + 'status': 'completed', + 'outputs': [{'type': 'text', 'text': 'Done.'}], + }, + ) + return httpx.Response(200, json={'models': []}) + + plugin = GoogleAI( + api_key='test-key', + timeout=5, + http_client_factory=lambda: httpx.AsyncClient(transport=httpx.MockTransport(handler)), + ) + ai = Genkit(plugins=[plugin]) + + await ai.generate_operation( + model='googleai/deep-research-pro-preview-12-2025', + prompt='Compare espresso grinders.', + config=DeepResearchConfig(timeout=300), + ) + await ai.generate( + model='googleai/antigravity-preview-05-2026', + prompt='Build a menu card.', + config=AntigravityConfig(timeout=60), + ) + + posts = [r for r in captured if r.method == 'POST' and '/interactions' in r.url.path] + assert len(posts) == 2 + for req in posts: + assert 'x-server-timeout' not in req.headers + assert [req.extensions['timeout']['read'] for req in posts] == [300.0, 60.0] + + +@pytest.mark.asyncio +async def test_lowercase_caller_server_timeout_header_does_not_duplicate() -> None: + """headers={'x-server-timeout': '20'} normalizes to X-Server-Timeout so google-genai sends one header.""" + captured: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured.append(request) + if request.method == 'GET': + return httpx.Response(200, json={'models': []}) + body = {'candidates': [{'content': {'role': 'model', 'parts': [{'text': 'ok'}]}, 'finishReason': 'STOP'}]} + return httpx.Response( + 200, content=json.dumps(body).encode('utf-8'), headers={'content-type': 'application/json'} + ) + + plugin = GoogleAI( + api_key='test-key', + timeout=60, + headers={'x-server-timeout': '20'}, + http_client_factory=lambda: httpx.AsyncClient(transport=httpx.MockTransport(handler)), + ) + ai = Genkit(plugins=[plugin]) + + await ai.generate(model='googleai/gemini-2.5-flash', prompt='Suggest a dish.') + await ai.generate(model='googleai/gemini-2.5-flash', prompt='Suggest a dish.', config=GeminiConfig(timeout=15)) + + posts = [r for r in captured if r.method == 'POST'] + assert len(posts) == 2 + first_raw = [v for k, v in posts[0].headers.raw if k.lower() == b'x-server-timeout'] + second_raw = [v for k, v in posts[1].headers.raw if k.lower() == b'x-server-timeout'] + assert first_raw == [b'20'] + assert second_raw == [b'15'] diff --git a/packages/genkit-google-genai/tests/gemini_tool_config_test.py b/packages/genkit-google-genai/tests/gemini_tool_config_test.py new file mode 100644 index 000000000..897f8d010 --- /dev/null +++ b/packages/genkit-google-genai/tests/gemini_tool_config_test.py @@ -0,0 +1,191 @@ +# 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 + +"""toolConfig on the wire: built-in tools next to function tools.""" + +import json +from collections.abc import Awaitable, Callable +from typing import Any +from unittest.mock import MagicMock + +import httpx +import pytest +from genkit_google_genai import GeminiConfig, GoogleAI +from genkit_google_genai._models._gemini import GeminiModel +from genkit_google_genai._models._utils import PartConverter +from google import genai +from google.genai import types as genai_types + +from genkit import Genkit, Message, Part, Role +from genkit.model import ModelRequest, ToolDefinition + + +def _fake_gemini_api(bodies: list[dict[str, Any]]) -> Callable[..., Awaitable[httpx.Response]]: + """Stand-in for httpx.AsyncClient.send that answers generateContent and records each POST body.""" + + async def send(_client: httpx.AsyncClient, request: httpx.Request, **_: object) -> httpx.Response: + if request.method == 'GET': + return httpx.Response(200, json={'models': []}, request=request) + bodies.append(json.loads(request.content)) + return httpx.Response( + 200, + json={ + 'candidates': [ + {'content': {'role': 'model', 'parts': [{'text': '{"dish": "pho"}'}]}, 'finishReason': 'STOP'} + ] + }, + request=request, + ) + + return send + + +def _app(monkeypatch: pytest.MonkeyPatch, bodies: list[dict[str, Any]]) -> Genkit: + monkeypatch.setattr(httpx.AsyncClient, 'send', _fake_gemini_api(bodies)) + ai = Genkit(plugins=[GoogleAI(api_key='fake-key')]) + + @ai.tool(name='lookup_menu') + async def lookup_menu(dish: str) -> str: + """Check whether a dish is on today's menu.""" + return 'in stock' + + return ai + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'builtin', + [ + GeminiConfig(google_search=True), + GeminiConfig(url_context=True), + GeminiConfig(code_execution=True), + GeminiConfig(file_search_store_names=['fileSearchStores/menu']), + ], + ids=['google_search', 'url_context', 'code_execution', 'file_search'], +) +async def test_builtin_tool_with_function_tool_opts_in_to_server_side_invocations( + monkeypatch: pytest.MonkeyPatch, builtin: GeminiConfig +) -> None: + """Gemini 3 rejects built-in + function tools unless toolConfig.includeServerSideToolInvocations is set.""" + bodies: list[dict[str, Any]] = [] + ai = _app(monkeypatch, bodies) + + await ai.generate( + model='googleai/gemini-flash-latest', prompt='Is the pho in stock?', tools=['lookup_menu'], config=builtin + ) + + assert bodies[-1]['toolConfig'] == {'includeServerSideToolInvocations': True} + + +@pytest.mark.asyncio +async def test_server_side_flag_merges_with_tool_choice(monkeypatch: pytest.MonkeyPatch) -> None: + """The flag rides next to the function calling mode.""" + bodies: list[dict[str, Any]] = [] + ai = _app(monkeypatch, bodies) + + await ai.generate( + model='googleai/gemini-flash-latest', + prompt='Is the pho in stock?', + tools=['lookup_menu'], + tool_choice='auto', + config=GeminiConfig(google_search=True), + ) + + assert bodies[-1]['toolConfig'] == { + 'functionCallingConfig': {'mode': 'AUTO'}, + 'includeServerSideToolInvocations': True, + } + + +@pytest.mark.asyncio +async def test_function_tools_alone_send_no_tool_config(monkeypatch: pytest.MonkeyPatch) -> None: + """Only function tools: nothing to opt in to.""" + bodies: list[dict[str, Any]] = [] + ai = _app(monkeypatch, bodies) + + await ai.generate(model='googleai/gemini-flash-latest', prompt='Is the pho in stock?', tools=['lookup_menu']) + + assert 'toolConfig' not in bodies[-1] + + +@pytest.mark.asyncio +async def test_builtin_tool_alone_sends_no_tool_config(monkeypatch: pytest.MonkeyPatch) -> None: + """Only a built-in tool: nothing to opt in to.""" + bodies: list[dict[str, Any]] = [] + ai = _app(monkeypatch, bodies) + + await ai.generate( + model='googleai/gemini-flash-latest', prompt='Pho history?', config=GeminiConfig(google_search=True) + ) + + assert 'toolConfig' not in bodies[-1] + + +def _tool_request(**kwargs: Any) -> ModelRequest: # noqa: ANN401 + return ModelRequest( + messages=kwargs.pop('messages', [Message(role=Role.USER, content=[Part.from_text('Is the pho in stock?')])]), + tools=[ToolDefinition(name='lookup_menu', description='d', input_schema={'type': 'object'})], + **kwargs, + ) + + +@pytest.mark.asyncio +async def test_vertex_never_sends_server_side_flag() -> None: + """Vertex AI has no includeServerSideToolInvocations; google-genai raises if it is set.""" + client = MagicMock(spec=genai.Client) + client.vertexai = True + model = GeminiModel('gemini-3.5-flash', client) + + cfg = await model._genkit_to_googleai_cfg(_tool_request(config=GeminiConfig(google_search=True))) + + assert cfg is not None + assert cfg.tool_config is None + + +@pytest.mark.asyncio +async def test_function_tools_disable_sdk_afc() -> None: + """Genkit runs the tools; google-genai AFC is off so it doesn't warn about FunctionDeclarations.""" + client = MagicMock(spec=genai.Client) + client.vertexai = False + model = GeminiModel('gemini-flash-latest', client) + + cfg = await model._genkit_to_googleai_cfg(_tool_request(config=GeminiConfig(google_search=True))) + + assert cfg is not None + assert cfg.automatic_function_calling == genai_types.AutomaticFunctionCallingConfig(disable=True) + + +@pytest.mark.asyncio +async def test_server_side_tool_parts_round_trip() -> None: + """toolCall / toolResponse parts survive Genkit history and go back unchanged, signature included.""" + tool_call = genai_types.Part( + tool_call=genai_types.ToolCall(id='c1', tool_type=genai_types.ToolType.GOOGLE_SEARCH_WEB, args={'q': 'pho'}), + thought_signature=b'sig-1', + ) + tool_response = genai_types.Part( + tool_response=genai_types.ToolResponse( + id='c1', tool_type=genai_types.ToolType.GOOGLE_SEARCH_WEB, response={'results': ['pho is soup']} + ) + ) + + genkit_call = PartConverter.from_gemini(tool_call) + genkit_response = PartConverter.from_gemini(tool_response) + + assert genkit_call.custom == {'geminiToolCall': {'id': 'c1', 'toolType': 'GOOGLE_SEARCH_WEB', 'args': {'q': 'pho'}}} + assert genkit_call.metadata is not None and 'thoughtSignature' in genkit_call.metadata + rehydrated = Part.model_validate_json(genkit_call.model_dump_json(by_alias=True)) + assert await PartConverter.to_gemini(rehydrated) == tool_call + assert await PartConverter.to_gemini(genkit_response) == tool_response diff --git a/packages/genkit-google-genai/tests/models/context_cache_test.py b/packages/genkit-google-genai/tests/models/context_cache_test.py new file mode 100644 index 000000000..e9796e95e --- /dev/null +++ b/packages/genkit-google-genai/tests/models/context_cache_test.py @@ -0,0 +1,144 @@ +# 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 + +"""Context caching: no model allowlist, code_execution conflict, context_cache=False.""" + +import pytest +from genkit_google_genai import GeminiConfig +from genkit_google_genai._models._context_caching._utils import validate_context_cache_request +from genkit_google_genai._models._gemini import GeminiModel +from google.genai import types as genai_types +from pytest_mock import MockerFixture + +from genkit import GenkitError, Message, Part, Role +from genkit.model import ModelContext, ModelRequest + +_MENU = 'Tasting menu: 1. Smoked salmon tartine 2. Pesto gnocchi 3. Olive oil cake. ' * 50 + + +def _cached_request(config: object = None) -> ModelRequest: + return ModelRequest( + messages=[ + Message(role=Role.USER, content=[Part.from_text(_MENU)], metadata={'cache': {'ttlSeconds': 300}}), + Message(role=Role.USER, content=[Part.from_text('Which dish is nut-free?')]), + ], + config=config, + ) + + +@pytest.mark.parametrize('model', ['gemini-flash-latest', 'gemini-pro-latest', 'gemini-3.8-flash', 'gemini-2.5-flash']) +def test_any_model_passes_validation(model: str) -> None: + """The API decides which models can cache; the plugin no longer blocks live models.""" + assert validate_context_cache_request(_cached_request(), model) is True + + +@pytest.mark.parametrize( + 'config', + [ + GeminiConfig(code_execution=True), + {'code_execution': True}, + {'codeExecution': True}, + ], + ids=['typed', 'dict-snake', 'dict-camel'], +) +def test_code_execution_conflicts_with_cache(config: object) -> None: + """code_execution in typed or dict configs fails validation.""" + with pytest.raises(GenkitError) as raised: + validate_context_cache_request(_cached_request(config), 'gemini-flash-latest') + assert raised.value.status == 'INVALID_ARGUMENT' + assert 'code execution' in raised.value.message + + +@pytest.mark.parametrize( + 'config', + [ + GeminiConfig(google_search=True), + GeminiConfig(google_search_types=['web']), + GeminiConfig(url_context=True), + GeminiConfig(file_search_store_names=['fileSearchStores/menu']), + {'googleSearch': True}, + {'urlContext': True}, + {'fileSearchStoreNames': ['fileSearchStores/menu']}, + ], + ids=[ + 'google_search', + 'google_search_types', + 'url_context', + 'file_search_store_names', + 'dict-googleSearch', + 'dict-urlContext', + 'dict-fileSearchStoreNames', + ], +) +@pytest.mark.asyncio +async def test_builtin_tools_conflict_with_cache_before_creating_remote_cache( + mocker: MockerFixture, config: object +) -> None: + """Built-in tools fail before caches.list or caches.create runs.""" + with pytest.raises(GenkitError) as raised: + validate_context_cache_request(_cached_request(config), 'gemini-flash-latest') + assert raised.value.status == 'INVALID_ARGUMENT' + + if isinstance(config, GeminiConfig): + client = mocker.AsyncMock() + client.vertexai = False + gemini = GeminiModel('gemini-flash-latest', client) + with pytest.raises(GenkitError) as gen_raised: + await gemini.generate(_cached_request(config), ModelContext()) + assert gen_raised.value.status == 'INVALID_ARGUMENT' + client.aio.caches.list.assert_not_called() + client.aio.caches.create.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'config', + [{'context_cache': False}, {'contextCache': False}], + ids=['snake', 'camel'], +) +async def test_dict_context_cache_false_ignores_cache_markers(mocker: MockerFixture, config: dict[str, object]) -> None: + """Dict configs with context_cache=False or contextCache=False skip cache creation in _build_messages.""" + client = mocker.AsyncMock() + client.vertexai = False + gemini = GeminiModel('gemini-flash-latest', client) + + contents, cached = await gemini._build_messages(_cached_request(config), 'gemini-flash-latest', client=client) + + assert cached is None + assert len(contents) == 2 + client.aio.caches.list.assert_not_called() + client.aio.caches.create.assert_not_called() + + +@pytest.mark.asyncio +async def test_context_cache_false_ignores_cache_markers(mocker: MockerFixture) -> None: + """context_cache=False sends every message inline and never touches the caches API.""" + client = mocker.AsyncMock() + client.vertexai = False + client.aio.models.generate_content.return_value = genai_types.GenerateContentResponse( + candidates=[ + genai_types.Candidate(content=genai_types.Content(parts=[genai_types.Part(text='Olive oil cake.')])) + ] + ) + gemini = GeminiModel('gemini-flash-latest', client) + + await gemini.generate(_cached_request(GeminiConfig(context_cache=False)), ModelContext()) + + client.aio.caches.list.assert_not_called() + client.aio.caches.create.assert_not_called() + kwargs = client.aio.models.generate_content.call_args.kwargs + assert len(kwargs['contents']) == 2 + assert kwargs['config'] is None or kwargs['config'].cached_content is None 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..6a14f8d57 100644 --- a/packages/genkit-google-genai/tests/part_converter_fidelity_test.py +++ b/packages/genkit-google-genai/tests/part_converter_fidelity_test.py @@ -259,3 +259,25 @@ async def test_gemma_history_replay_strips_reasoning_and_thought_signatures(mock ] # Caller's Part metadata is not mutated in place. assert signed_answer.metadata == {**sig_meta, 'source': 'menu'} + + +@pytest.mark.asyncio +async def test_parts_without_a_gemini_field_are_not_sent(mocker: MockerFixture) -> None: + """Replaying Part.data (a2ui) used to send an empty Part(), which Gemini rejects.""" + 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='ok')]))] + ) + request = ModelRequest( + messages=[ + Message(role=Role.USER, content=[Part.from_text('Show the menu.')]), + Message(role=Role.MODEL, content=[Part.from_text('Here it is.'), Part.from_data({'surface': 'menu'})]), + Message(role=Role.MODEL, content=[Part.from_data({'surface': 'cart'})]), + Message(role=Role.USER, content=[Part.from_text('Add pesto.')]), + ] + ) + + await GeminiModel('gemini-flash-latest', client).generate(request, ModelContext()) + + contents = client.aio.models.generate_content.call_args.kwargs['contents'] + assert [[p.text for p in c.parts] for c in contents] == [['Show the menu.'], ['Here it is.'], ['Add pesto.']] diff --git a/packages/genkit-google-genai/tests/part_converter_test.py b/packages/genkit-google-genai/tests/part_converter_test.py index 0299e04e5..6c36ea487 100644 --- a/packages/genkit-google-genai/tests/part_converter_test.py +++ b/packages/genkit-google-genai/tests/part_converter_test.py @@ -415,7 +415,46 @@ def refuse(request: httpx.Request) -> httpx.Response: class TestPartValidationEdges: - """A malformed thought signature raises INVALID_ARGUMENT.""" + """Malformed base64, custom tool payloads, and tool-response media raise INVALID_ARGUMENT.""" + + @pytest.mark.asyncio + async def test_multipart_tool_response_reraises_genkit_error(self) -> None: + part = Part( + tool_response=ToolResponse( + name='shot', + output={'ok': True}, + content=[{'media': {'contentType': 'image/png', 'url': '/etc/passwd'}}], + ) + ) + with pytest.raises(GenkitError) as raised: + await PartConverter.to_gemini(part) + assert raised.value.status == 'INVALID_ARGUMENT' + assert '/etc/passwd' not in raised.value.message + + @pytest.mark.asyncio + async def test_legacy_tool_response_data_uri_validates_and_strips_whitespace(self) -> None: + valid = Part( + tool_response=ToolResponse( + name='shot', + output={'ok': True, 'content': [{'media': {'url': 'data:image/png;base64,YWJj\n ZGVm'}}]}, + ) + ) + got = await PartConverter.to_gemini(valid) + assert isinstance(got, genai.types.Part) + assert got.function_response is not None and got.function_response.parts is not None + assert got.function_response.parts[0].inline_data is not None + assert got.function_response.parts[0].inline_data.data == b'abcdef' + assert got.function_response.parts[0].inline_data.mime_type == 'image/png' + + corrupt = Part( + tool_response=ToolResponse( + name='shot', + output={'ok': True, 'content': [{'media': {'url': 'data:image/png;base64,YWJj%%%!'}}]}, + ) + ) + with pytest.raises(GenkitError) as raised: + await PartConverter.to_gemini(corrupt) + assert raised.value.status == 'INVALID_ARGUMENT' @pytest.mark.asyncio async def test_malformed_thought_signature_is_invalid_argument(self) -> None: @@ -424,3 +463,19 @@ async def test_malformed_thought_signature_is_invalid_argument(self) -> None: await PartConverter.to_gemini(part) assert raised.value.status == 'INVALID_ARGUMENT' assert '%%%not-valid-base64!' not in raised.value.message + + @pytest.mark.asyncio + @pytest.mark.parametrize( + 'custom', + [ + {'geminiToolCall': 'not-an-object'}, + {'geminiToolResponse': 'not-an-object'}, + ], + ids=['bad-tool-call', 'bad-tool-response'], + ) + async def test_malformed_server_side_tool_custom_payload_is_invalid_argument( + self, custom: dict[str, object] + ) -> None: + with pytest.raises(GenkitError) as raised: + await PartConverter.to_gemini(Part(custom=custom)) + assert raised.value.status == 'INVALID_ARGUMENT' diff --git a/packages/genkit-google-genai/tests/vertexai_project_test.py b/packages/genkit-google-genai/tests/vertexai_project_test.py index 3d7e3ffa0..8335c7981 100644 --- a/packages/genkit-google-genai/tests/vertexai_project_test.py +++ b/packages/genkit-google-genai/tests/vertexai_project_test.py @@ -122,7 +122,7 @@ async def test_gemini_resolve_request_client_missing_project_is_failed_precondit await model._resolve_request_client( ModelRequest( messages=[Message(role=Role.USER, content=[Part.from_text('hi')])], - config={'api_version': 'v1'}, + config={'apiVersion': 'v1'}, ) ) From d015f6adaa86f533972aca36ca585656c1c256ee Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 00:34:49 -0600 Subject: [PATCH 3/4] fix(py/google-genai): read the backend from _is_vertex() for the timeout floor and server-side tool flag Keyless GoogleAI() (#49) has no plugin client, so self._client.vertexai raised AttributeError on a context.secrets call that mixed built-in and function tools or set a timeout. _is_vertex() falls back to the plugin kwargs. --- .../genkit_google_genai/_models/_gemini.py | 4 +-- .../tests/gemini_tool_config_test.py | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) 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 6de813871..79c0160e0 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 @@ -2663,7 +2663,7 @@ async def _genkit_to_googleai_cfg( } # The Gemini API rejects X-Server-Timeout under 10s with a 400; # the header is floored there and httpx still enforces `ms`. - headers['X-Server-Timeout'] = server_timeout_header(ms, vertexai=bool(self._client.vertexai)) + headers['X-Server-Timeout'] = server_timeout_header(ms, vertexai=self._is_vertex()) http_options.headers = headers cfg.http_options = http_options return cfg @@ -2681,7 +2681,7 @@ async def _genkit_to_googleai_cfg( def _needs_server_side_tool_invocations(self, tools: list[genai_types.Tool]) -> bool: """Whether *tools* mixes function declarations with built-in tools on the Gemini API.""" - if self._client.vertexai: + if self._is_vertex(): return False has_functions = any(tool.function_declarations for tool in tools) has_builtin = any(not tool.function_declarations for tool in tools) diff --git a/packages/genkit-google-genai/tests/gemini_tool_config_test.py b/packages/genkit-google-genai/tests/gemini_tool_config_test.py index 897f8d010..3c5fff827 100644 --- a/packages/genkit-google-genai/tests/gemini_tool_config_test.py +++ b/packages/genkit-google-genai/tests/gemini_tool_config_test.py @@ -134,6 +134,40 @@ async def test_builtin_tool_alone_sends_no_tool_config(monkeypatch: pytest.Monke assert 'toolConfig' not in bodies[-1] +@pytest.mark.asyncio +async def test_keyless_plugin_with_tenant_key_sends_flag_and_timeout_floor(monkeypatch: pytest.MonkeyPatch) -> None: + """Keyless GoogleAI() has no plugin client; the per-call key still gets the flag and the 10s header.""" + bodies: list[dict[str, Any]] = [] + headers: list[str | None] = [] + send = _fake_gemini_api(bodies) + + async def record(client: httpx.AsyncClient, request: httpx.Request, **kw: object) -> httpx.Response: + headers.append(request.headers.get('x-server-timeout')) + return await send(client, request, **kw) + + monkeypatch.setattr(httpx.AsyncClient, 'send', record) + monkeypatch.delenv('GEMINI_API_KEY', raising=False) + monkeypatch.delenv('GOOGLE_API_KEY', raising=False) + monkeypatch.delenv('GOOGLE_GENAI_API_KEY', raising=False) + ai = Genkit(plugins=[GoogleAI()]) + + @ai.tool(name='lookup_menu') + async def lookup_menu(dish: str) -> str: + """Check whether a dish is on today's menu.""" + return 'in stock' + + await ai.generate( + model='googleai/gemini-flash-latest', + prompt='Is the pho in stock?', + tools=['lookup_menu'], + config=GeminiConfig(google_search=True, timeout=3.0), + context={'secrets': {'api_key': 'tenant-key'}}, + ) + + assert bodies[-1]['toolConfig'] == {'includeServerSideToolInvocations': True} + assert headers[-1] == '10' + + def _tool_request(**kwargs: Any) -> ModelRequest: # noqa: ANN401 return ModelRequest( messages=kwargs.pop('messages', [Message(role=Role.USER, content=[Part.from_text('Is the pho in stock?')])]), From ab96ac0448ab60cac3b2905cae1629dc32178b4b Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 16 Nov 2026 10:35:52 -0600 Subject: [PATCH 4/4] 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'