diff --git a/packages/genkit-google-genai/README.md b/packages/genkit-google-genai/README.md index a4c2fcde3..139be501c 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 bd8d13268..a99bef976 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -158,6 +158,7 @@ strip_ref_prefixes, ) from genkit_google_genai._models._sdk_config import ( + GEMINI_API_MIN_SERVER_TIMEOUT_SECONDS, check_timeout_seconds, check_vertex_project, is_missing_vertex_project, @@ -736,6 +737,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, @@ -746,6 +748,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) @@ -770,13 +773,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. @@ -1615,6 +1629,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. @@ -1630,6 +1645,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 ( @@ -1649,6 +1669,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 f48dca11b..ba4515daa 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 @@ -40,6 +40,7 @@ reject_bool_timeout, request_client_kwargs, sdk_config_error, + server_timeout_header, split_sdk_fields, timeout_seconds_to_ms, ) @@ -772,7 +773,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.' ), ) @@ -819,7 +821,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." ), ) @@ -2238,14 +2241,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. @@ -2488,6 +2486,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: @@ -2501,15 +2501,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, @@ -2666,10 +2667,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( @@ -2691,7 +2704,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=self._is_vertex()) http_options.headers = headers cfg.http_options = http_options return cfg @@ -2707,6 +2722,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._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) + 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 1c11e3bef..0f3e570dd 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 @@ -355,6 +355,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 572fc2366..13a1ddf09 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 @@ -63,6 +66,8 @@ 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. @@ -164,6 +169,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' @@ -248,6 +256,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) @@ -265,13 +275,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: @@ -294,21 +303,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. @@ -325,8 +330,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, @@ -337,6 +346,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, @@ -382,6 +394,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 @@ -480,6 +518,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 @@ -551,9 +605,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 @@ -562,43 +618,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 @@ -619,3 +713,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..3c5fff827 --- /dev/null +++ b/packages/genkit-google-genai/tests/gemini_tool_config_test.py @@ -0,0 +1,225 @@ +# 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] + + +@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?')])]), + 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 8b3f239f1..a141959f3 100644 --- a/packages/genkit-google-genai/tests/part_converter_fidelity_test.py +++ b/packages/genkit-google-genai/tests/part_converter_fidelity_test.py @@ -298,3 +298,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 d4dbd0678..70abc9dee 100644 --- a/packages/genkit-google-genai/tests/part_converter_test.py +++ b/packages/genkit-google-genai/tests/part_converter_test.py @@ -414,6 +414,65 @@ def refuse(request: httpx.Request) -> httpx.Response: await PartConverter.to_gemini(part) +class TestPartValidationEdges: + """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 + @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' + + class TestThoughtSignatureDecoding: """Signatures decode from standard or URL-safe base64; a bad one is dropped, not fatal.""" diff --git a/packages/genkit-google-genai/tests/vertexai_project_test.py b/packages/genkit-google-genai/tests/vertexai_project_test.py index e2b0fcba7..55c54b5f6 100644 --- a/packages/genkit-google-genai/tests/vertexai_project_test.py +++ b/packages/genkit-google-genai/tests/vertexai_project_test.py @@ -154,7 +154,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'}, ) )