diff --git a/packages/genkit-google-genai/README.md b/packages/genkit-google-genai/README.md index 649e0619..a4c2fcde 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 `{}` 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 8af002e7..bd8d1326 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -159,6 +159,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, ) @@ -297,10 +300,17 @@ 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. """ + check_vertex_project(client_kwargs) 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 is_missing_vertex_project(client_kwargs, e): + raise missing_vertex_project_error(e) from e + raise def _call_client(plugin: GoogleAI | VertexAI, context: dict[str, Any] | None) -> genai.Client: @@ -1241,7 +1251,8 @@ def __init__( # base_url set the SDK skips its own ADC lookup, evaluator registration # needs a concrete project, 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. + # 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) @@ -1251,12 +1262,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 c612046d..68384dac 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, @@ -195,11 +196,247 @@ 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 [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_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 + 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: + 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]: + """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. Fragments are collected per run and joined once, so the + cost is linear in reply length. + """ + 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 = 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.kind == 'reasoning': + prev.metadata = part.metadata + prev.merged = True + continue + 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 + 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('')] + + +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 - return {'promptFeedback': feedback.model_dump(mode='json', by_alias=True, exclude_none=True)} + 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 +2125,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) @@ -2045,33 +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.', - ) - - 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 new_request_client(kwargs) async def _generate( self, @@ -2121,8 +2325,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 +2341,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 +2373,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, _StreamCandidateMetadata] = {} saw_chunk = False saw_candidates = False try: @@ -2188,11 +2403,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 + 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: @@ -2213,11 +2435,14 @@ 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({idx: acc.result() for idx, acc in candidates_metadata.items()}) + ), ) @cached_property @@ -2260,19 +2485,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 +2563,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 +2573,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 +2634,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/_sdk_config.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_sdk_config.py index fa4f0562..1c11e3be 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 8585331d..572fc236 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,11 @@ logger = get_logger(__name__) +# 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. # Some media hosts (Wikipedia, for one) answer 403 to requests without a real @@ -192,8 +198,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 +223,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 +304,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 +317,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 +331,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 +341,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 +363,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 +379,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 +401,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,32 +453,59 @@ 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('') @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): - return base64.b64decode(thought_sig) - 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: @@ -568,5 +612,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/src/genkit_google_genai/_models/_veo.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py index 9fd90503..5dc847c8 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 @@ -331,17 +332,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 0ed51b23..70be6549 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 new file mode 100644 index 00000000..c8307768 --- /dev/null +++ b/packages/genkit-google-genai/tests/models/gemini_candidate_metadata_test.py @@ -0,0 +1,409 @@ +# 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()) + + # ModelResponse fills an unset custom with {}, so callers never see None. + assert response.custom == {} + 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.""" + + 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'}, + ] + # 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: + """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( + candidates=[ + _candidate( + 'Pesto ', + grounding_metadata=genai_types.GroundingMetadata( + web_search_queries=['pesto pine nuts'], + search_entry_point=genai_types.SearchEntryPoint(rendered_content='