Skip to content
5 changes: 3 additions & 2 deletions packages/genkit-google-genai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 33 additions & 2 deletions packages/genkit-google-genai/src/genkit_google_genai/_google.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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.

Expand All @@ -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 (
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -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'],
Expand All @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
reject_bool_timeout,
request_client_kwargs,
sdk_config_error,
server_timeout_header,
split_sdk_fields,
timeout_seconds_to_ms,
)
Expand Down Expand Up @@ -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.'
),
)

Expand Down Expand Up @@ -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."
),
)

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand All @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading