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 68a6da3c2..595dba337 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -598,6 +598,7 @@ def __init__( max_retries: int | None = None, http_client_factory: Callable[[], httpx.AsyncClient] | None = None, legacy_response_schema: bool = False, + experimental_debug_traces: bool = False, ) -> None: """Initializes the GoogleAI plugin. @@ -666,6 +667,12 @@ def __init__( ``responseSchema`` field instead of ``responseJsonSchema``, converted to its format; a schema that cannot be converted raises ``INVALID_ARGUMENT``. Defaults to False. + experimental_debug_traces: Enables additional debug traces (e.g. + raw model API call details). Each Interactions API call + (Deep Research, Antigravity, Lyria) gets an ``httpRequest`` + trace span with the endpoint, the request body, the headers + (API key hidden) and the response body. Experimental; the + span contents may change. Defaults to False. Raises: ValueError: If `api_key` is not provided and the 'GEMINI_API_KEY' @@ -698,6 +705,7 @@ def __init__( self._http_client_factory = _loop_local_http_client(http_client_factory) self._base_url_pinned = bool(self._client_kwargs['http_options'].base_url) self._legacy_response_schema = legacy_response_schema + self._experimental_debug_traces = experimental_debug_traces self._list_actions_cache: list[Action | BackgroundAction[Any, Any]] | None = None @loop_local_client @@ -728,6 +736,7 @@ def _interactions_client_options(self) -> ClientOptions: # The getter, not a client: Interactions calls it per request so # each event loop gets its own client. http_client_factory=self._http_client_factory, + experimental_debug_traces=self._experimental_debug_traces, ) def _plugin_api_key(self) -> str | 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 c1614f3af..2f7bc9246 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 @@ -23,12 +23,14 @@ from urllib.parse import quote import httpx +from genkit_google_genai._interactions._errors import api_error_fields, interaction_error_status, unwrap_error_body from genkit_google_genai._interactions._options import ClientOptions from genkit_google_genai._provider_errors import TRANSPORT_ERRORS, transport_error from google.genai.interactions import Interaction from genkit import GenkitError -from genkit.plugin_api import GENKIT_USER_AGENT, loop_local_client, provider_error +from genkit.plugin_api import GENKIT_USER_AGENT, StatusName, loop_local_client, provider_error +from genkit.telemetry import SpanContext, run_in_new_span DEFAULT_API_VERSION = 'v1beta' DEFAULT_BASE_URL = 'https://generativelanguage.googleapis.com' @@ -129,6 +131,8 @@ async def cancel_interaction( api_key=api_key, client_options=client_options, allow_empty=True, + # Not traced, as in JS (cancelInteraction calls makeRequest directly). + trace=False, ) except GenkitError as error: if error.status == 'CANCELLED': @@ -139,6 +143,34 @@ async def cancel_interaction( return interaction.model_copy(update={'status': 'cancelled'}) +def redact(value: str) -> str: + """`` (N characters)``, as in JS buildTraceMetadataInput.""" + return f' ({len(value)} characters)' + + +def trace_input( + url: str, + request_headers: Mapping[str, str], + json_body: dict[str, object] | None, + client_options: ClientOptions | None, +) -> dict[str, object]: + """The ``httpRequest`` span input, the same shape as JS buildTraceMetadataInput. + + The API key header is hidden. Interactions requests carry the model in + the body, so there's no separate ``model`` field (JS adds one only for + generateContent). + """ + safe_headers = { + name: redact(value) if name.lower() in ('x-goog-api-key', 'authorization') else value + for name, value in request_headers.items() + } + traced: dict[str, object] = {'apiEndpoint': url, 'request': json_body, 'headers': safe_headers} + timeout = client_options.timeout if client_options else None + if timeout: + traced['options'] = {'timeout': timeout} + return traced + + async def request( *, method: str, @@ -147,14 +179,62 @@ async def request( client_options: ClientOptions | None, json_body: dict[str, object] | None = None, allow_empty: bool = False, + trace: bool = True, ) -> Interaction | None: - """Issue one Interactions HTTP call and parse the Interaction body.""" + """Issue one Interactions HTTP call and parse the Interaction body. + + With ``experimental_debug_traces`` on the client options (and ``trace``), + the call runs in an ``httpRequest`` span whose input is the endpoint, + the request body and the headers (API key hidden), and whose output is + the response body, as in JS. + """ # Auth/key headers are per-request; the client is just the transport. + request_headers = headers(api_key=api_key, client_options=client_options) + + async def call(span: SpanContext | None = None) -> object: + return await send( + method=method, + url=url, + request_headers=request_headers, + client_options=client_options, + json_body=json_body, + allow_empty=allow_empty, + ) + + if trace and client_options is not None and client_options.experimental_debug_traces: + # The span output is the response body as received, like JS. + body = await run_in_new_span( + 'httpRequest', + call, + input=trace_input(url, request_headers, json_body, client_options), + ) + else: + body = await call() + if body is None: + return None + try: + return Interaction.model_validate(body) + except Exception as error: + raise GenkitError( + status='INTERNAL', + message=f'Unable to parse Interaction response from {url}: {error}', + ) from error + + +async def send( + *, + method: str, + url: str, + request_headers: dict[str, str], + client_options: ClientOptions | None, + json_body: dict[str, object] | None = None, + allow_empty: bool = False, +) -> object: + """Send one Interactions HTTP call; return the JSON body (None for an allowed empty one) or raise.""" # The timeout always goes on the request so a caller's own client gets the # same budget as the default one instead of httpx's 5 second default. http_client_factory = client_options.http_client_factory if client_options else None client = http_client_factory() if http_client_factory is not None else _http_client() - request_headers = headers(api_key=api_key, client_options=client_options) timeout = timeout_seconds(client_options) try: @@ -177,28 +257,36 @@ async def request( message=f'Received an empty response from {url}', ) try: - return Interaction.model_validate(response.json()) - except Exception as error: + body: object = response.json() + except json.JSONDecodeError as error: raise GenkitError( status='INTERNAL', message=f'Unable to parse Interaction response from {url}: {error}', ) from error + return body error_message = response.text error_detail: object | None = None + # An Interactions error code (e.g. `quota_exceeded`, `model_not_found`) + # is more precise than the HTTP status, so it wins when it's known. + code_status: StatusName | None = None try: - payload: object = response.json() + # The Interactions API sometimes wraps the error in a one-element + # array (e.g. a bad API key). + payload: object = unwrap_error_body(response.json()) error_detail = payload - if isinstance(payload, Mapping): - api_error = payload.get('error') - if isinstance(api_error, Mapping) and api_error.get('message') is not None: - error_message = str(api_error['message']) + api_message, api_code = api_error_fields(payload) + if api_message is not None: + error_message = api_message + code_status = interaction_error_status(api_code) except json.JSONDecodeError: pass message = f'Request to {url} failed with HTTP {response.status_code} {response.reason_phrase}: {error_message}' cause = httpx.HTTPStatusError(message, request=httpx.Request(method, url), response=response) - error = provider_error(cause, http_status=response.status_code, headers=response.headers, message=message) + error = provider_error( + cause, http_status=response.status_code, status=code_status, headers=response.headers, message=message + ) if isinstance(error_detail, Mapping): error.details.update(error_detail) raise error from cause diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_converters.py b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_converters.py index d1193b570..cd6c053c1 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_converters.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_converters.py @@ -20,10 +20,18 @@ import copy import json +import re from typing import Any, Literal, cast +from urllib.parse import urlparse +from genkit_google_genai._interactions._errors import interaction_error_status, is_interaction_content_block_code + +# Private SDK module: the SDK exports this type only here. It goes away with +# the SDK types when the plugin gets its own Interactions types. +from google.genai._gaos.types import UnrecognizedStr from google.genai.interactions import ( AudioContent, + AudioContentParam, CodeExecutionCallStep, CodeExecutionCallStepParam, CodeExecutionResultStep, @@ -31,6 +39,7 @@ Content, ContentParam, DocumentContent, + DocumentContentParam, FunctionCallStep, FunctionCallStepParam, FunctionParam, @@ -42,7 +51,9 @@ GoogleSearchResultStep, GoogleSearchResultStepParam, ImageContent, + ImageContentParam, Interaction, + ModalityTokens, ModelOutputStep, ModelOutputStepParam, Step, @@ -56,6 +67,7 @@ UserInputStep, UserInputStepParam, VideoContent, + VideoContentParam, ) from pydantic import BaseModel @@ -87,7 +99,7 @@ THOUGHT_CUSTOM = 'thought' # Wire function_result.content is only text/image blocks, not a JSON array. CONTENT_BLOCK_TYPES = frozenset({'text', 'image'}) -# Code execution only ever runs Python, and the wire rejects any other value. +# The language when a code execution step names none. CODE_LANGUAGE: Literal['python'] = 'python' FAILED_MESSAGE = 'Interaction failed' @@ -114,13 +126,16 @@ # Chat generate can pause for a tool; a background job cannot. BACKGROUND_INTERRUPT_UNSUPPORTED = 'Background models do not support interrupts' -# Interactions splits media into typed content blocks, chosen by mime prefix. -MEDIA_CONTENT_TYPES: tuple[tuple[str, str], ...] = ( - ('image/', 'image'), - ('audio/', 'audio'), - ('video/', 'video'), - ('application/pdf', 'document'), -) +# Content types guessed from a URL's file extension when a media part has +# none (same list as the JS plugin). +KNOWN_MIME_TYPES: dict[str, str] = { + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'png': 'image/png', + 'mp4': 'video/mp4', + 'pdf': 'application/pdf', +} +YOUTUBE_HOSTS = frozenset({'youtube.com', 'youtu.be'}) # Turns a Genkit role into the side of the transcript it belongs on. Tool # results are part of the user's side; system prompts aren't turns at all. @@ -159,8 +174,10 @@ def interaction_error_message(interaction: Interaction) -> str | None: def error_from_provider_code(code: object, cause: BaseException) -> GenkitError | None: """Turn an error code the Interactions API reported into a GenkitError. - Top-level errors carry a string code (a canonical name like - ``RESOURCE_EXHAUSTED``, or a number); step errors carry a gRPC int. + Top-level errors carry a string code: an Interactions code like + ``service_unavailable`` or ``malformed_function_call`` (see + ``INTERACTION_ERROR_CODE_TO_STATUS``), a canonical name like + ``RESOURCE_EXHAUSTED``, or a number; step errors carry a gRPC int. Numbers 1-16 are gRPC codes and 400-599 are HTTP codes. Anything else, and any code that only maps to OK or UNKNOWN, returns None so the caller can look at the next error. @@ -174,6 +191,8 @@ def error_from_provider_code(code: object, cause: BaseException) -> GenkitError error = provider_error(cause, status=GRPC_STATUS_NAMES[number]) else: return None + elif (status := interaction_error_status(text)) is not None: + error = provider_error(cause, status=status) elif text.upper() in GRPC_STATUS_NAMES: error = provider_error(cause, status=cast(StatusName, text.upper())) else: @@ -183,6 +202,31 @@ def error_from_provider_code(code: object, cause: BaseException) -> GenkitError return error +def first_error(interaction: Interaction) -> tuple[object, str | None]: + """The code and message of the interaction's first top-level error, if any.""" + for err in interaction.errors or []: + return err.code, err.message + return None, None + + +def blocked_response(interaction: Interaction) -> ModelResponse | None: + """The response for an interaction that failed on a content-policy block, or None. + + Safety, recitation and the other content-policy codes return a response + with finish_reason 'blocked' and no content, like a blocked + generateContent response, instead of raising. + """ + code, message = first_error(interaction) + if not is_interaction_content_block_code(code): + return None + return model_response( + interaction, + content=[], + finish_reason=FinishReason.BLOCKED, + finish_message=message or interaction_error_message(interaction) or FAILED_MESSAGE, + ) + + def interaction_error(interaction: Interaction, cause: BaseException) -> GenkitError: """The error for the first failure on an Interaction that has a usable code, else UNKNOWN.""" for err in interaction.errors or []: @@ -280,20 +324,76 @@ def to_interaction_content(part: Part) -> ContentParam | None: return None +def extract_mime_type(url: str) -> str: + """The content type a URL names: a data URL's header, or a known file extension; else ''.""" + if not url.startswith('data:'): + extension = url.rsplit('.', 1)[-1] + return KNOWN_MIME_TYPES.get(extension, '') + header, separator, _ = url[len('data:') :].partition(',') + if not separator: + return '' + return header.removesuffix(';base64').strip() + + +def is_youtube_url(url: str) -> bool: + """True for a youtube.com or youtu.be link.""" + host = urlparse(url).hostname or '' + return host.removeprefix('www.').removeprefix('m.') in YOUTUBE_HOSTS + + +def video_block(part: Part, *, mime_type: str | None = None) -> VideoContentParam: + """A video block, with ``metadata['processing']`` (`static` / `agentic`) when the part sets it.""" + video: VideoContentParam = {'type': 'video'} + if mime_type: + video['mime_type'] = UnrecognizedStr(mime_type) + processing = (part.metadata or {}).get('processing') + if isinstance(processing, str): + video['processing'] = UnrecognizedStr(processing) + return video + + def to_interaction_media(part: Part) -> ContentParam: - """Convert a media part to an Interactions image/audio/video/document block.""" + """Convert a media part to an Interactions image/audio/video/document block. + + Image, audio and video types get their own block; every other type is + sent as a ``document`` (PDF, CSV, Word, Excel, ...): the server decides + which types it accepts and returns a clear error for the rest; its list + has grown beyond the PDF and CSV in the published spec. + """ if part.media is None: raise GenkitError(status='INVALID_ARGUMENT', message='Media part missing media') - content_type = part.media.content_type + url = part.media.url + content_type = part.media.content_type or extract_mime_type(url) + if not content_type: - raise GenkitError(status='INVALID_ARGUMENT', message='Media part missing contentType') - block_type = next((name for prefix, name in MEDIA_CONTENT_TYPES if content_type.startswith(prefix)), None) - if block_type is None: - raise GenkitError(status='INVALID_ARGUMENT', message=f'Unsupported media type: {content_type}') + if url.startswith('data:'): + raise GenkitError(status='INVALID_ARGUMENT', message='Media part missing contentType') + # A URI whose type can't be worked out (e.g. a YouTube link or a Files + # API URI). The server works out the type itself, so it's sent without + # a mime_type, as the generateContent path does. YouTube links are + # video; anything else is sent as a document (checked live: the + # server still treats a YouTube link sent as a document as video). + if is_youtube_url(url): + youtube = video_block(part) + youtube['uri'] = url + return youtube + unknown: DocumentContentParam = {'type': 'document', 'uri': url} + return unknown + + # The SDK types each mime_type as a few known values or its own + # `UnrecognizedStr`; any other type (e.g. Word) goes through that. + mime_type = UnrecognizedStr(content_type) + block: ImageContentParam | AudioContentParam | VideoContentParam | DocumentContentParam + if content_type.startswith('image/'): + block = {'type': 'image', 'mime_type': mime_type} + elif content_type.startswith('audio/'): + block = {'type': 'audio', 'mime_type': mime_type} + elif content_type.startswith('video/'): + block = video_block(part, mime_type=content_type) + else: + block = {'type': 'document', 'mime_type': mime_type} - block: dict[str, Any] = {'type': block_type, 'mime_type': content_type} # Inline data URLs travel as base64; anything else is a reference the API fetches. - url = part.media.url if url.startswith('data:'): if ',' not in url: raise GenkitError( @@ -303,7 +403,7 @@ def to_interaction_media(part: Part) -> ContentParam: block['data'] = url.split(',', 1)[1] else: block['uri'] = url - return cast(ContentParam, block) + return block def to_interaction_role(role: str) -> InteractionRole: @@ -500,10 +600,18 @@ def to_server_tool_step(custom: dict[str, Any], metadata: dict[str, Any]) -> Ste return search_result if EXECUTABLE_CODE in custom: code = custom[EXECUTABLE_CODE] + stored_language = code.get('language') + # The Interactions API takes 'python' or 'bash'; generateContent parts + # say 'PYTHON', which it rejects (400, seen live). Cast: the SDK types + # `language` as 'python' only; our own Interactions types remove it. + language = cast( + Literal['python'], + (stored_language.lower() if isinstance(stored_language, str) else '') or CODE_LANGUAGE, + ) code_call: CodeExecutionCallStepParam = { 'type': 'code_execution_call', 'id': metadata.get(CALL_ID, ''), - 'arguments': {'code': code.get('code'), 'language': CODE_LANGUAGE}, + 'arguments': {'code': code.get('code'), 'language': language}, } return code_call if CODE_EXECUTION_RESULT in custom: @@ -553,6 +661,42 @@ def to_content_step(role: InteractionRole, content: list[ContentParam]) -> StepP return user_step +def ensure_code_execution_ids(messages: list[Message]) -> list[Message]: + """Give code execution calls and results without a call ID matching IDs. + + History saved from generateContent has no ``callId`` on its + ``executableCode`` / ``codeExecutionResult`` parts, and the Interactions + API rejects an empty id. A call without one gets + ``genkit-code-execution-id-N`` and the next result without one gets the + same ID; a result with no call waiting gets + ``genkit-code-execution-orphan-id-N`` (like ``ensure_tool_ids`` does for + tool requests). Parts that have an ID keep it. Returns copies. + """ + pending: list[str] = [] + next_id = 0 + result: list[Message] = [] + for message in messages: + content: list[Part] = [] + for part in message.content: + custom = part.custom or {} + is_call = EXECUTABLE_CODE in custom + if (part.metadata or {}).get(CALL_ID) or not (is_call or CODE_EXECUTION_RESULT in custom): + content.append(part) + continue + if is_call: + call_id = f'genkit-code-execution-id-{next_id}' + next_id += 1 + pending.append(call_id) + elif pending: + call_id = pending.pop(0) + else: + call_id = f'genkit-code-execution-orphan-id-{next_id}' + next_id += 1 + content.append(with_metadata(part, CALL_ID, call_id)) + result.append(message.model_copy(update={'content': content})) + return result + + def to_interaction_steps(messages: list[Message]) -> list[StepParam]: """Convert Genkit messages to Interactions API steps. @@ -563,7 +707,7 @@ def to_interaction_steps(messages: list[Message]) -> list[StepParam]: to the end of the turn. """ steps: list[StepParam] = [] - for message in messages: + for message in ensure_code_execution_ids(messages): role = to_interaction_role(message.role) inline: list[ContentParam] = [] @@ -695,12 +839,29 @@ def from_function_result_step(step: FunctionResultStep) -> Part: }) +def interaction_media_mime_type(content: ImageContent | AudioContent | DocumentContent | VideoContent) -> str | None: + """The content type of an Interactions media block. + + Audio that comes with ``data`` but no ``mime_type`` is raw 16-bit PCM: the + server streams single-voice TTS that way (``{type: 'audio', data, + sample_rate, channels}``, seen live Nov 2026), while it labels the same + audio ``audio/l16; rate=24000; channels=1`` in other cases (e.g. two + speakers). The label is built from the ``sample_rate`` and ``channels`` it + sends (24000 and 1 when missing), so the audio can be played and joined. + A given ``mime_type`` always wins. + """ + if content.mime_type or not isinstance(content, AudioContent) or not content.data: + return content.mime_type + return f'audio/l16; rate={content.sample_rate or 24000}; channels={content.channels or 1}' + + def from_media_content(content: ImageContent | AudioContent | DocumentContent | VideoContent) -> Part: """Convert wire media content to a Genkit media part.""" + mime_type = interaction_media_mime_type(content) url = content.uri - if content.data and content.mime_type: - url = f'data:{content.mime_type};base64,{content.data}' - return Part(media=Media(url=url or '', content_type=content.mime_type)) + if content.data and mime_type: + url = f'data:{mime_type};base64,{content.data}' + return Part(media=Media(url=url or '', content_type=mime_type)) def from_text_content(content: TextContent) -> Part: @@ -791,8 +952,19 @@ def interaction_message_metadata(interaction: Interaction) -> dict[str, Any] | N return metadata or None +def snake_to_camel(name: str) -> str: + """``google_search`` -> ``googleSearch``.""" + return re.sub(r'_([a-z0-9])', lambda match: match.group(1).upper(), name) + + def usage_from_interaction(usage: Usage) -> GenerationUsage: - """Map Interactions Usage onto Genkit GenerationUsage.""" + """Map Interactions Usage onto Genkit GenerationUsage. + + The per-modality breakdowns are token counts, so they go in ``custom`` + as e.g. ``inputTextTokens`` / ``outputImageTokens``: Genkit's + ``input_characters``, ``input_images``, ... count characters and media + parts (``with_basic_usage_stats`` adds those where the request is known). + """ response_usage = GenerationUsage( input_tokens=usage.total_input_tokens, output_tokens=usage.total_output_tokens, @@ -800,33 +972,53 @@ def usage_from_interaction(usage: Usage) -> GenerationUsage: cached_content_tokens=usage.total_cached_tokens, thoughts_tokens=usage.total_thought_tokens, ) - for modality_token in usage.input_tokens_by_modality or []: - match modality_token.modality: - case 'text': - response_usage.input_characters = modality_token.tokens - case 'image': - response_usage.input_images = modality_token.tokens - case 'audio': - response_usage.input_audio_files = modality_token.tokens - case 'video': - response_usage.input_videos = modality_token.tokens - case _: - pass - for modality_token in usage.output_tokens_by_modality or []: - match modality_token.modality: - case 'text': - response_usage.output_characters = modality_token.tokens - case 'image': - response_usage.output_images = modality_token.tokens - case 'audio': - response_usage.output_audio_files = modality_token.tokens - case 'video': - response_usage.output_videos = modality_token.tokens - case _: - pass + # Genkit has no standard fields for these. + custom: dict[str, float] = {} + + def add_modality_tokens(direction: str, breakdown: list[ModalityTokens] | None) -> None: + for item in breakdown or []: + if item.modality and isinstance(item.tokens, int): + key = f'{direction}{item.modality[:1].upper()}{item.modality[1:]}Tokens' + custom[key] = custom.get(key, 0) + item.tokens + + add_modality_tokens('input', usage.input_tokens_by_modality) + add_modality_tokens('output', usage.output_tokens_by_modality) + # Tokens loaded by tools, e.g. video frames read during agentic video + # understanding. + if usage.total_tool_use_tokens: + custom['toolUseTokens'] = usage.total_tool_use_tokens + # How many times each grounding tool was used, e.g. `googleSearchCount`. + for tool_count in usage.grounding_tool_count or []: + if tool_count.type and isinstance(tool_count.count, int): + key = f'{snake_to_camel(tool_count.type)}Count' + custom[key] = custom.get(key, 0) + tool_count.count + if custom: + response_usage.custom = custom return response_usage +def with_basic_usage_stats(response: ModelResponse, request_messages: list[Message]) -> ModelResponse: + """Add character and media-part counts to an Interactions response's usage. + + ``input_characters``, ``input_images``, ... are counted from the request + messages and the response message, the same way as on generateContent + models (``GenerationUsage.from_messages``). Telemetry reads these fields. + The token counts from the API are kept and win over the basic counts. + + Call it on the final response, with the request's messages. Background + models (Deep Research) don't have the request when checked, so they don't + get these counts. + """ + output = response.message or Message(role='model', content=[]) + usage = GenerationUsage.from_messages(request_messages, output) + if response.usage is not None: + for field, value in response.usage: + if value is not None: + setattr(usage, field, value) + response.usage = usage + return response + + def parts_from_steps(steps: list[Step], *, status: str | None = None) -> list[Part]: """Flatten interaction steps into Genkit parts, dropping empty ones.""" pending_ids = get_pending_function_call_ids(steps, status) @@ -905,10 +1097,14 @@ def from_interaction_sync(interaction: Interaction) -> ModelResponse: generate that ran out of tokens does not look like a clean stop. In-flight statuses raise FAILED_PRECONDITION — this helper is not a poll loop. A failed interaction raises a GenkitError with the status its - error code maps to, or UNKNOWN when there's no usable code. + error code maps to, or UNKNOWN when there's no usable code, except a + content-policy block, which returns a response with finish_reason + 'blocked'. """ status = interaction.status if status == 'failed': + if (blocked := blocked_response(interaction)) is not None: + return blocked failure = ValueError(interaction_error_message(interaction) or FAILED_MESSAGE) raise interaction_error(interaction, failure) from failure if status == 'cancelled': @@ -957,7 +1153,10 @@ def from_interaction(interaction: Interaction) -> Operation: elif status == 'failed': # Always exit the poll loop on failure; leaving done unset hangs forever. op.done = True - op.error = Failure(message=interaction_error_message(interaction) or FAILED_MESSAGE) + if (blocked := blocked_response(interaction)) is not None: + op.output = blocked + else: + op.error = Failure(message=interaction_error_message(interaction) or FAILED_MESSAGE) elif status == 'requires_action': # Chat generate can pause for a tool. A background job cannot — there # is no interrupt/resume on generate_operation — so end the poll diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_errors.py b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_errors.py new file mode 100644 index 000000000..efeab6636 --- /dev/null +++ b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_errors.py @@ -0,0 +1,139 @@ +# 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 + +"""Interactions API error codes and error bodies (shared by the client and the converters).""" + +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict, ValidationError + +from genkit.plugin_api import StatusName + +# Content-policy blocks (safety, recitation, ...). A failed interaction with +# one of these codes is returned as a response with finish_reason 'blocked' +# (like a blocked generateContent response) rather than raised. When raised +# (e.g. in an error event), they map to FAILED_PRECONDITION, which isn't +# retried: the same input would be blocked again. +INTERACTION_CONTENT_BLOCK_CODES: frozenset[str] = frozenset({ + 'safety', + 'recitation', + 'language', + 'prohibited_content', + 'spii', + 'blocklist', + 'image_safety', + 'image_prohibited_content', + 'image_recitation', + 'image_other', + 'content_blocked', + 'jailbreak', + 'model_armor', +}) + +# Interactions API error codes and the Genkit status for each. The API +# reports errors as `{code: string, message: string}`; the spec doesn't list +# the codes, so this is the set the API returns (with the HTTP status the +# API pairs each one with). +INTERACTION_ERROR_CODE_TO_STATUS: dict[str, StatusName] = { + # Generation failures reported with `status: 'failed'` + `errors[]` after + # the server's own retries ran out. The server message says to retry, so + # these are ABORTED ("retry at a higher level"), which Retry retries. + 'malformed_function_call': 'ABORTED', + 'unexpected_tool_call': 'ABORTED', + 'no_image': 'ABORTED', + **dict.fromkeys(INTERACTION_CONTENT_BLOCK_CODES, 'FAILED_PRECONDITION'), + 'service_unavailable': 'UNAVAILABLE', # 503: server or model overloaded + 'rate_limit_exceeded': 'RESOURCE_EXHAUSTED', # 429: RPM/TPM limits + 'quota_exceeded': 'RESOURCE_EXHAUSTED', # 429: RPD/daily limits + 'invalid_request': 'INVALID_ARGUMENT', # 400: general bad request + 'parameter_unknown': 'INVALID_ARGUMENT', # 400: unrecognized field + 'failed_precondition': 'FAILED_PRECONDITION', # 400 + 'out_of_range': 'OUT_OF_RANGE', # 400 + # 400: over the agent's max token limit. The same request fails the same + # way, so deliberately not RESOURCE_EXHAUSTED (which is retried). + 'agent_max_token_limit': 'INVALID_ARGUMENT', + 'model_not_found': 'NOT_FOUND', # 404 + 'not_found': 'NOT_FOUND', # 404 + 'authentication': 'UNAUTHENTICATED', # 401 + 'permission_denied': 'PERMISSION_DENIED', # 403 + 'already_exists': 'ALREADY_EXISTS', # 409 + 'aborted': 'ABORTED', # 409 + 'cancelled': 'CANCELLED', # 499 + 'deadline_exceeded': 'DEADLINE_EXCEEDED', # 504 + 'api_error': 'INTERNAL', # 500 + 'unimplemented': 'UNIMPLEMENTED', # 501 +} + + +def interaction_error_status(code: object) -> StatusName | None: + """The Genkit status for an Interactions error code (case-insensitive), or None. + + Only the API's string codes: numeric codes (HTTP or gRPC) are mapped by + the caller, which knows which kind it has. + """ + if not isinstance(code, str): + return None + return INTERACTION_ERROR_CODE_TO_STATUS.get(code.strip().lower()) + + +def is_interaction_content_block_code(code: object) -> bool: + """True for a content-policy error code (safety, recitation, blocklist, ...).""" + return isinstance(code, str) and code.strip().lower() in INTERACTION_CONTENT_BLOCK_CODES + + +# The error body of a failed API call, read through these models so the type +# checkers know the field types. Only the fields the plugin reads; others are +# allowed. TODO(own-types PR): move these into the plugin's own Interactions +# types. +class ApiError(BaseModel): + """The ``error`` object of an API error body.""" + + model_config = ConfigDict(extra='allow') + + message: object = None + code: object = None + + +class ApiErrorBody(BaseModel): + """An API error body: ``{"error": {"code": ..., "message": ...}}``.""" + + model_config = ConfigDict(extra='allow') + + error: ApiError | None = None + + +def api_error_fields(body: object) -> tuple[str | None, object]: + """The message and code of an API error body, or ``(None, None)`` when it isn't one.""" + try: + parsed = ApiErrorBody.model_validate(body) + except ValidationError: + return None, None + if parsed.error is None: + return None, None + message = parsed.error.message + return (str(message) if message is not None else None), parsed.error.code + + +def unwrap_error_body(body: object) -> object: + """Unwrap an error body sent as a one-element JSON array. + + The Interactions API sometimes wraps its error that way: a bad API key + gives ``[{"error": {"code": 400, "message": "API key not valid. ..."}}]`` + (seen with the Dart plugin, Nov 2026). Anything else is returned as is. + """ + if isinstance(body, list) and len(body) == 1: + return body[0] + return body diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_options.py b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_options.py index 7cbedf23c..391829116 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_options.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_options.py @@ -49,6 +49,10 @@ class ClientOptions(BaseModel): # Only the plugin sets this; a request config can't swap the connection. # A getter, called per request, so each event loop gets its own client. http_client_factory: Callable[[], httpx.AsyncClient] | None = Field(default=None, exclude=True) + # Only the plugin sets this (`GoogleAI(experimental_debug_traces=True)`), + # as in JS. Each create/get call then runs in an `httpRequest` span with + # the request and response (API key hidden). + experimental_debug_traces: bool = Field(default=False, exclude=True) def merge(self, overrides: ClientOptions | dict[str, Any] | None) -> Self: """Return a copy with non-null override fields applied.""" diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_antigravity.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_antigravity.py index 2cf9fb61a..01225be6a 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_antigravity.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_antigravity.py @@ -26,6 +26,7 @@ ensure_tool_ids, from_interaction_sync, to_interaction_tool, + with_basic_usage_stats, ) from genkit_google_genai._interactions._options import ClientOptions from genkit_google_genai._models._interactions_registry import antigravity_model_info @@ -268,7 +269,7 @@ async def run(request: ModelRequest[AntigravityConfig], ctx: ModelContext) -> Mo create_kwargs['tools'] = tools created = await create_interaction(api_key, deep_merge(create_kwargs, extra), merged_options) - return from_interaction_sync(created) + return with_basic_usage_stats(from_interaction_sync(created), request.messages) return Model( name, diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_lyria.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_lyria.py index fbcd36679..1112adaa3 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_lyria.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_lyria.py @@ -26,6 +26,7 @@ from_interaction_sync, split_system_instruction, to_interaction_steps, + with_basic_usage_stats, ) from genkit_google_genai._interactions._options import ClientOptions, ResponseModality from genkit_google_genai._models._interactions_registry import lyria_model_info @@ -138,7 +139,7 @@ async def run(request: ModelRequest[LyriaConfig], ctx: ModelContext) -> ModelRes require_interaction_steps(steps) created = await create_interaction(api_key, deep_merge(create_kwargs, extra), merged_options) - return from_interaction_sync(created) + return with_basic_usage_stats(from_interaction_sync(created), request.messages) return Model( name, diff --git a/packages/genkit-google-genai/tests/interactions/interactions_client_test.py b/packages/genkit-google-genai/tests/interactions/interactions_client_test.py index dd1e24b63..79fcfaa81 100644 --- a/packages/genkit-google-genai/tests/interactions/interactions_client_test.py +++ b/packages/genkit-google-genai/tests/interactions/interactions_client_test.py @@ -24,6 +24,7 @@ import httpx import pytest +from genkit_google_genai import GoogleAI from genkit_google_genai._interactions import _client as interactions_client from genkit_google_genai._interactions._client import ( API_REVISION, @@ -212,6 +213,167 @@ async def test_429_retry_after_header_sets_retry_delay(http_client: MagicMock) - assert exc_info.value.details['error'] == {'message': 'slow down'} +@pytest.mark.asyncio +async def test_error_body_sent_as_a_list_is_unwrapped(http_client: MagicMock) -> None: + """A bad API key comes back as a one-element JSON array (seen with the Dart plugin).""" + body = { + 'error': { + 'code': 400, + 'message': 'API key not valid. Please pass a valid API key.', + 'status': 'INVALID_ARGUMENT', + } + } + http_client.request.return_value = httpx.Response(400, json=[body]) + with patch.object(interactions_client, '_http_client', return_value=http_client): + with pytest.raises(GenkitError) as exc_info: + await create_interaction('key', {'model': 'lyria'}) + assert exc_info.value.status == 'INVALID_ARGUMENT' + assert 'API key not valid. Please pass a valid API key.' in str(exc_info.value) + assert '[{' not in str(exc_info.value) + assert exc_info.value.details['error'] == body['error'] + + +@pytest.mark.asyncio +async def test_interactions_error_code_wins_over_the_http_status(http_client: MagicMock) -> None: + """`model_not_found` on a 400 is NOT_FOUND, not INVALID_ARGUMENT.""" + http_client.request.return_value = mock_response( + status_code=400, + json_body={'error': {'code': 'model_not_found', 'message': 'no such model'}}, + ) + with patch.object(interactions_client, '_http_client', return_value=http_client): + with pytest.raises(GenkitError) as exc_info: + await create_interaction('key', {'model': 'lyria-9'}) + assert exc_info.value.status == 'NOT_FOUND' + assert 'no such model' in str(exc_info.value) + + +@pytest.mark.asyncio +async def test_unknown_interactions_error_code_keeps_the_http_status(http_client: MagicMock) -> None: + http_client.request.return_value = mock_response( + status_code=503, + json_body={'error': {'code': 'something_new', 'message': 'busy'}}, + ) + with patch.object(interactions_client, '_http_client', return_value=http_client): + with pytest.raises(GenkitError) as exc_info: + await create_interaction('key', {'model': 'lyria'}) + assert exc_info.value.status == 'UNAVAILABLE' + + +class SpanRecorder: + """Stands in for genkit.telemetry.run_in_new_span: records the call, runs the body.""" + + def __init__(self) -> None: + self.calls: list[dict[str, Any]] = [] + + async def __call__(self, name: str, fn: Any, *, input: object = None, **_: Any) -> Any: # noqa: A002 + record: dict[str, Any] = {'name': name, 'input': input} + self.calls.append(record) + record['output'] = await fn(MagicMock()) + return record['output'] + + +@pytest.mark.asyncio +async def test_traces_create_interaction_with_experimental_debug_traces(http_client: MagicMock) -> None: + """Same span as JS createInteraction: endpoint, request, headers (key hidden); output = response.""" + response_body = {'id': 'ix-1', 'status': 'completed', 'model': 'gemini-3.8-flash'} + http_client.request.return_value = mock_response(json_body=response_body) + recorder = SpanRecorder() + request_body: dict[str, object] = {'model': 'gemini-3.8-flash', 'input': 'hi'} + with ( + patch.object(interactions_client, '_http_client', return_value=http_client), + patch.object(interactions_client, 'run_in_new_span', recorder), + ): + result = await create_interaction('secret-key12', request_body, ClientOptions(experimental_debug_traces=True)) + + assert result.id == 'ix-1' + assert len(recorder.calls) == 1 + span = recorder.calls[0] + assert span['name'] == 'httpRequest' + assert span['input'] == { + 'apiEndpoint': 'https://generativelanguage.googleapis.com/v1beta/interactions', + 'request': request_body, + 'headers': { + 'content-type': 'application/json', + 'x-goog-api-client': GENKIT_USER_AGENT, + 'api-revision': API_REVISION, + 'x-goog-api-key': ' (12 characters)', + }, + } + assert span['output'] == response_body + + +@pytest.mark.asyncio +async def test_traces_get_interaction_and_the_timeout(http_client: MagicMock) -> None: + http_client.request.return_value = mock_response(json_body={'id': 'ix-9', 'status': 'in_progress'}) + recorder = SpanRecorder() + with ( + patch.object(interactions_client, '_http_client', return_value=http_client), + patch.object(interactions_client, 'run_in_new_span', recorder), + ): + await get_interaction('key', 'ix-9', ClientOptions(experimental_debug_traces=True, timeout=1500)) + + span = recorder.calls[0] + assert span['input']['apiEndpoint'].endswith('/interactions/ix-9') + assert span['input']['request'] is None + assert span['input']['options'] == {'timeout': 1500} + + +@pytest.mark.asyncio +async def test_no_trace_by_default(http_client: MagicMock) -> None: + http_client.request.return_value = mock_response(json_body={'id': 'ix-1', 'status': 'completed'}) + recorder = SpanRecorder() + with ( + patch.object(interactions_client, '_http_client', return_value=http_client), + patch.object(interactions_client, 'run_in_new_span', recorder), + ): + await create_interaction('key', {'model': 'm'}) + await create_interaction('key', {'model': 'm'}, ClientOptions()) + assert recorder.calls == [] + + +@pytest.mark.asyncio +async def test_cancel_is_not_traced(http_client: MagicMock) -> None: + """As in JS: cancelInteraction calls makeRequest directly, without a span.""" + http_client.request.return_value = mock_response(content=b'') + recorder = SpanRecorder() + with ( + patch.object(interactions_client, '_http_client', return_value=http_client), + patch.object(interactions_client, 'run_in_new_span', recorder), + ): + result = await cancel_interaction('key', 'ix-1', ClientOptions(experimental_debug_traces=True)) + assert result.status == 'cancelled' + assert recorder.calls == [] + + +@pytest.mark.asyncio +async def test_traced_call_still_raises_errors(http_client: MagicMock) -> None: + http_client.request.return_value = mock_response( + status_code=400, json_body={'error': {'code': 'invalid_request', 'message': 'bad'}} + ) + recorder = SpanRecorder() + with ( + patch.object(interactions_client, '_http_client', return_value=http_client), + patch.object(interactions_client, 'run_in_new_span', recorder), + ): + with pytest.raises(GenkitError) as exc_info: + await create_interaction('key', {'model': 'm'}, ClientOptions(experimental_debug_traces=True)) + assert exc_info.value.status == 'INVALID_ARGUMENT' + assert len(recorder.calls) == 1 + + +def test_google_ai_passes_experimental_debug_traces_to_interactions_calls() -> None: + traced = GoogleAI(api_key='k', experimental_debug_traces=True) + assert traced._interactions_client_options().experimental_debug_traces + assert not GoogleAI(api_key='k')._interactions_client_options().experimental_debug_traces + + +def test_a_request_override_cannot_turn_on_debug_traces() -> None: + """Plugin-only, as in JS: merge() ignores it (excluded from the dump).""" + plugin = ClientOptions(experimental_debug_traces=True) + assert plugin.merge(ClientOptions(timeout=5)).experimental_debug_traces is True + assert ClientOptions().merge(ClientOptions(experimental_debug_traces=True)).experimental_debug_traces is False + + @pytest.mark.asyncio async def test_empty_success_body_is_internal_error(http_client: MagicMock) -> None: http_client.request.return_value = mock_response(content=b'') diff --git a/packages/genkit-google-genai/tests/interactions/interactions_converters_test.py b/packages/genkit-google-genai/tests/interactions/interactions_converters_test.py index 9227757f8..581020b8b 100644 --- a/packages/genkit-google-genai/tests/interactions/interactions_converters_test.py +++ b/packages/genkit-google-genai/tests/interactions/interactions_converters_test.py @@ -36,11 +36,12 @@ to_interaction_tool, to_thought_step, usage_from_interaction, + with_basic_usage_stats, ) from google.genai.interactions import Content, Interaction, Step, ThoughtStep, Usage from pydantic import BaseModel, TypeAdapter -from genkit import GenkitError, Message, Part +from genkit import GenkitError, Media, Message, Part from genkit.model import ToolDefinition, ToolRequest, ToolResponse ContentAdapter: TypeAdapter[Content] = TypeAdapter(Content) @@ -224,11 +225,96 @@ def test_document(self) -> None: result = to_interaction_content(Part.from_media('gs://bucket/doc.pdf', content_type='application/pdf')) assert result == {'type': 'document', 'uri': 'gs://bucket/doc.pdf', 'mime_type': 'application/pdf'} - def test_unsupported_media_raises(self) -> None: - with pytest.raises(GenkitError, match='Unsupported media type') as raised: - to_interaction_content(Part.from_media('https://example.com/x', content_type='text/plain')) + def test_csv_is_a_document(self) -> None: + result = to_interaction_content(Part.from_media('data:text/csv;base64,DATA', content_type='text/csv')) + assert result == {'type': 'document', 'data': 'DATA', 'mime_type': 'text/csv'} + + def test_word_and_excel_are_documents(self) -> None: + # User report (JS 1.43): these threw "Unsupported media type", although + # the server accepts them. + docx = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + xlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + assert to_interaction_content(Part.from_media(f'data:{docx};base64,DATA', content_type=docx)) == { + 'type': 'document', + 'data': 'DATA', + 'mime_type': docx, + } + assert to_interaction_content(Part.from_media('gs://bucket/sheet.xlsx', content_type=xlsx)) == { + 'type': 'document', + 'uri': 'gs://bucket/sheet.xlsx', + 'mime_type': xlsx, + } + + def test_other_content_types_are_left_for_the_server_to_accept_or_reject(self) -> None: + result = to_interaction_content(Part.from_media('gs://bucket/notes.txt', content_type='text/plain')) + assert result == {'type': 'document', 'uri': 'gs://bucket/notes.txt', 'mime_type': 'text/plain'} + + def test_youtube_url_without_content_type_is_video_without_mime_type(self) -> None: + url = 'https://www.youtube.com/watch?v=abc123' + assert to_interaction_content(Part(media=Media(url=url))) == {'type': 'video', 'uri': url} + assert to_interaction_content(Part(media=Media(url='https://youtu.be/abc123'))) == { + 'type': 'video', + 'uri': 'https://youtu.be/abc123', + } + + def test_other_uri_without_known_content_type_is_document_without_mime_type(self) -> None: + url = 'https://generativelanguage.googleapis.com/v1beta/files/abc123' + assert to_interaction_content(Part(media=Media(url=url))) == {'type': 'document', 'uri': url} + + def test_content_type_from_a_known_file_extension(self) -> None: + assert to_interaction_content(Part(media=Media(url='gs://bucket/doc.pdf'))) == { + 'type': 'document', + 'uri': 'gs://bucket/doc.pdf', + 'mime_type': 'application/pdf', + } + + def test_content_type_from_a_data_url(self) -> None: + assert to_interaction_content(Part(media=Media(url='data:image/png;base64,DATA'))) == { + 'type': 'image', + 'data': 'DATA', + 'mime_type': 'image/png', + } + + def test_data_url_without_content_type_raises(self) -> None: + with pytest.raises(GenkitError, match='Media part missing contentType') as raised: + to_interaction_content(Part(media=Media(url='data:;base64,DATA'))) assert raised.value.status == 'INVALID_ARGUMENT' + def test_sends_metadata_processing_on_a_youtube_video(self) -> None: + part = Part(media=Media(url='https://www.youtube.com/watch?v=abc123'), metadata={'processing': 'agentic'}) + assert to_interaction_content(part) == { + 'type': 'video', + 'uri': 'https://www.youtube.com/watch?v=abc123', + 'processing': 'agentic', + } + + def test_sends_metadata_processing_on_inline_and_uri_videos(self) -> None: + inline = Part( + media=Media(url='data:video/mp4;base64,AAAA', content_type='video/mp4'), + metadata={'processing': 'static'}, + ) + assert to_interaction_content(inline) == { + 'type': 'video', + 'mime_type': 'video/mp4', + 'data': 'AAAA', + 'processing': 'static', + } + files_api = 'https://generativelanguage.googleapis.com/v1beta/files/abc123' + uri = Part(media=Media(url=files_api, content_type='video/mp4'), metadata={'processing': 'agentic'}) + assert to_interaction_content(uri) == { + 'type': 'video', + 'mime_type': 'video/mp4', + 'uri': files_api, + 'processing': 'agentic', + } + + def test_ignores_metadata_processing_on_media_that_is_not_video(self) -> None: + part = Part( + media=Media(url='data:image/png;base64,AAAA', content_type='image/png'), + metadata={'processing': 'agentic'}, + ) + assert to_interaction_content(part) == {'type': 'image', 'mime_type': 'image/png', 'data': 'AAAA'} + class TestToInteractionSteps: def test_tool_request(self) -> None: @@ -273,7 +359,7 @@ def test_system_role_rejected(self) -> None: to_interaction_steps(messages) assert raised.value.status == 'INVALID_ARGUMENT' - def test_code_execution_call_always_sends_python(self) -> None: + def test_code_execution_call_sends_the_language_lower_case(self) -> None: messages = [ Message( role='model', @@ -284,6 +370,7 @@ def test_code_execution_call_always_sends_python(self) -> None: ], ) ] + # The Interactions API only accepts lower-case values. assert to_interaction_steps(messages) == [ { 'type': 'code_execution_call', @@ -292,6 +379,71 @@ def test_code_execution_call_always_sends_python(self) -> None: } ] + def test_continues_code_execution_history_saved_from_generate_content(self) -> None: + # The part shapes the generateContent path produces: no callId, and + # language 'PYTHON', which the Interactions API rejects (400 "Supported + # values: 'python', 'bash'", seen live). Real generateContent + # signatures are accepted on the steps (seen live), so they're kept. + messages = [ + Message(role='user', content=[Part.from_text('Run some code.')]), + Message( + role='model', + content=[ + Part.from_custom( + {'executableCode': {'code': 'print(5117)', 'language': 'PYTHON'}}, + metadata={'thoughtSignature': 'sig1'}, + ), + Part.from_custom({'codeExecutionResult': {'outcome': 'OUTCOME_OK', 'output': '5117\n'}}), + Part.from_custom({'executableCode': {'code': 'print(1)'}}), + Part.from_custom({'codeExecutionResult': {'outcome': 'OUTCOME_OK', 'output': '1\n'}}), + Part.from_text('The answer is 5117.'), + ], + ), + ] + assert to_interaction_steps(messages) == [ + {'type': 'user_input', 'content': [{'type': 'text', 'text': 'Run some code.'}]}, + { + 'type': 'code_execution_call', + 'id': 'genkit-code-execution-id-0', + 'arguments': {'code': 'print(5117)', 'language': 'python'}, + 'signature': 'sig1', + }, + {'type': 'code_execution_result', 'call_id': 'genkit-code-execution-id-0', 'result': '5117\n'}, + { + 'type': 'code_execution_call', + 'id': 'genkit-code-execution-id-1', + 'arguments': {'code': 'print(1)', 'language': 'python'}, + }, + {'type': 'code_execution_result', 'call_id': 'genkit-code-execution-id-1', 'result': '1\n'}, + {'type': 'model_output', 'content': [{'type': 'text', 'text': 'The answer is 5117.'}]}, + ] + + def test_keeps_existing_code_execution_ids_and_bash_and_gives_a_lone_result_an_orphan_id(self) -> None: + messages = [ + Message( + role='model', + content=[ + Part.from_custom( + {'executableCode': {'code': 'ls', 'language': 'bash'}}, metadata={'callId': 'call_1'} + ), + Part.from_custom({'codeExecutionResult': {'output': 'a.txt\n'}}, metadata={'callId': 'call_1'}), + Part.from_custom({'codeExecutionResult': {'output': 'stray\n'}}), + ], + ) + ] + steps = to_interaction_steps(messages) + assert steps == [ + {'type': 'code_execution_call', 'id': 'call_1', 'arguments': {'code': 'ls', 'language': 'bash'}}, + {'type': 'code_execution_result', 'call_id': 'call_1', 'result': 'a.txt\n'}, + {'type': 'code_execution_result', 'call_id': 'genkit-code-execution-orphan-id-0', 'result': 'stray\n'}, + ] + + def test_code_execution_ids_do_not_change_the_callers_messages(self) -> None: + part = Part.from_custom({'executableCode': {'code': 'print(1)'}}) + messages = [Message(role='model', content=[part])] + to_interaction_steps(messages) + assert messages[0].content[0].metadata is None + def test_google_search_call(self) -> None: messages = [ Message( @@ -559,6 +711,44 @@ def test_image_resolution(self) -> None: 'metadata': {'resolution': 'high'}, } + def test_labels_audio_data_without_a_mime_type_as_l16(self) -> None: + # Streamed single-voice TTS deltas (no mime_type) assembled into the + # final response's content. + content_type = 'audio/l16; rate=24000; channels=1' + result = from_interaction_content( + ContentAdapter.validate_python({'type': 'audio', 'data': 'AAEC', 'channels': 1, 'sample_rate': 24000}) + ) + assert part_dict(result) == {'media': {'url': f'data:{content_type};base64,AAEC', 'contentType': content_type}} + + def test_audio_without_a_mime_type_uses_the_sample_rate_and_channels_sent(self) -> None: + result = from_interaction_content( + ContentAdapter.validate_python({'type': 'audio', 'data': 'AAEC', 'channels': 2, 'sample_rate': 16000}) + ) + assert result.media is not None + assert result.media.content_type == 'audio/l16; rate=16000; channels=2' + + def test_audio_without_a_mime_type_defaults_to_24khz_mono(self) -> None: + result = from_interaction_content(ContentAdapter.validate_python({'type': 'audio', 'data': 'AAEC'})) + assert result.media is not None + assert result.media.content_type == 'audio/l16; rate=24000; channels=1' + + def test_audio_mime_type_sent_by_the_server_wins(self) -> None: + result = from_interaction_content( + ContentAdapter.validate_python({ + 'type': 'audio', + 'data': 'AAEC', + 'mime_type': 'audio/wav', + 'sample_rate': 16000, + }) + ) + assert part_dict(result) == {'media': {'url': 'data:audio/wav;base64,AAEC', 'contentType': 'audio/wav'}} + + def test_audio_uri_without_a_mime_type_is_not_labelled(self) -> None: + result = from_interaction_content( + ContentAdapter.validate_python({'type': 'audio', 'uri': 'gs://bucket/clip.mp3'}) + ) + assert part_dict(result) == {'media': {'url': 'gs://bucket/clip.mp3'}} + def test_thought(self) -> None: step = ThoughtStep.model_validate({ 'type': 'thought', @@ -893,6 +1083,20 @@ def test_failed_uses_top_level_errors(self) -> None: assert result.error is not None assert result.error.message == 'Invalid prompt format' + def test_failed_content_block_is_a_blocked_output(self) -> None: + result = from_interaction( + Interaction.model_validate({ + 'id': '123', + 'status': 'failed', + 'errors': [{'code': 'recitation', 'message': 'Recitation detected.'}], + }) + ) + assert result.done is True + assert result.error is None + assert result.output is not None + assert result.output.finish_reason == 'blocked' + assert result.output.finish_message == 'Recitation detected.' + def test_requires_action_exits_poll_loop(self) -> None: interaction = Interaction.model_validate({ 'id': '123', @@ -1032,6 +1236,100 @@ def test_failed_with_unusable_code_is_unknown(self, code: str) -> None: assert raised.value.status == 'UNKNOWN' assert str(raised.value) == 'UNKNOWN: model crashed' + def test_returns_finish_reason_blocked_for_a_post_execution_safety_block(self) -> None: + result = from_interaction_sync( + Interaction.model_validate({ + 'id': 'int-1', + 'status': 'failed', + 'errors': [{'code': 'safety', 'message': 'Response blocked due to safety violations.'}], + }) + ) + assert result.finish_reason == 'blocked' + assert result.finish_message == 'Response blocked due to safety violations.' + assert result.message is not None + assert result.message.content == [] + assert result.message.metadata is not None + assert result.message.metadata.get('interactionId') == 'int-1' + + @pytest.mark.parametrize( + 'code', + [ + 'safety', + 'recitation', + 'language', + 'prohibited_content', + 'spii', + 'blocklist', + 'image_safety', + 'image_prohibited_content', + 'image_recitation', + 'image_other', + 'content_blocked', + 'jailbreak', + 'model_armor', + ], + ) + def test_returns_finish_reason_blocked_for_every_content_block_code(self, code: str) -> None: + result = from_interaction_sync( + Interaction.model_validate({'status': 'failed', 'errors': [{'code': code, 'message': 'blocked'}]}) + ) + assert result.finish_reason == 'blocked' + + def test_carries_usage_on_a_blocked_response(self) -> None: + result = from_interaction_sync( + Interaction.model_validate({ + 'status': 'failed', + 'errors': [{'code': 'safety', 'message': 'blocked'}], + 'usage': { + 'total_input_tokens': 10, + 'total_output_tokens': 0, + 'total_tokens': 10, + 'input_tokens_by_modality': [ + {'modality': 'text', 'tokens': 8}, + {'modality': 'image', 'tokens': 2}, + ], + }, + }) + ) + assert result.finish_reason == 'blocked' + assert result.usage is not None + assert result.usage.model_dump(exclude_none=True) == { + 'inputTokens': 10, + 'outputTokens': 0, + 'totalTokens': 10, + 'custom': {'inputTextTokens': 8, 'inputImageTokens': 2}, + } + + def test_raises_a_retryable_aborted_error_for_malformed_function_call(self) -> None: + advice = 'Model generated invalid JSON syntax and the output could not be parsed. Please retry the request.' + with pytest.raises(GenkitError) as raised: + from_interaction_sync( + Interaction.model_validate({ + 'status': 'failed', + 'errors': [{'code': 'malformed_function_call', 'message': advice}], + }) + ) + assert raised.value.status == 'ABORTED' + assert advice in str(raised.value) + + @pytest.mark.parametrize( + ('code', 'status'), + [ + ('unexpected_tool_call', 'ABORTED'), + ('no_image', 'ABORTED'), + ('service_unavailable', 'UNAVAILABLE'), + ('quota_exceeded', 'RESOURCE_EXHAUSTED'), + ('model_not_found', 'NOT_FOUND'), + ('agent_max_token_limit', 'INVALID_ARGUMENT'), + ], + ) + def test_raises_the_status_for_an_interactions_error_code(self, code: str, status: str) -> None: + with pytest.raises(GenkitError) as raised: + from_interaction_sync( + Interaction.model_validate({'status': 'failed', 'errors': [{'code': code, 'message': 'x'}]}) + ) + assert raised.value.status == status + def test_queued_is_failed_precondition(self) -> None: with pytest.raises(GenkitError, match='still running') as raised: from_interaction_sync(Interaction.model_validate({'id': '123', 'status': 'queued'})) @@ -1144,7 +1442,7 @@ def test_joins_multiple_system_turns(self) -> None: class TestUsageFromInteraction: - def test_maps_totals_and_video_modality(self) -> None: + def test_maps_totals_and_puts_modality_tokens_in_custom(self) -> None: usage = Usage.model_validate({ 'total_input_tokens': 10, 'total_output_tokens': 4, @@ -1160,5 +1458,117 @@ def test_maps_totals_and_video_modality(self) -> None: assert mapped.total_tokens == 14 assert mapped.cached_content_tokens == 2 assert mapped.thoughts_tokens == 1 - assert mapped.input_videos == 3 - assert mapped.output_videos == 1 + # Per-modality counts are tokens, not Genkit's media-part counts. + assert mapped.custom == {'inputVideoTokens': 3, 'outputVideoTokens': 1} + assert mapped.input_videos is None + assert mapped.output_videos is None + + def test_text_and_image_tokens_are_not_characters_or_images(self) -> None: + mapped = usage_from_interaction( + Usage.model_validate({ + 'total_input_tokens': 10, + 'total_output_tokens': 0, + 'total_tokens': 10, + 'input_tokens_by_modality': [ + {'modality': 'text', 'tokens': 8}, + {'modality': 'image', 'tokens': 2}, + ], + }) + ) + assert mapped.custom == {'inputTextTokens': 8, 'inputImageTokens': 2} + assert mapped.input_characters is None + assert mapped.input_images is None + + def test_reports_tool_use_tokens_in_custom(self) -> None: + mapped = usage_from_interaction( + Usage.model_validate({ + 'total_input_tokens': 416, + 'total_output_tokens': 393, + 'total_tool_use_tokens': 2054, + 'total_thought_tokens': 2117, + 'total_tokens': 4980, + }) + ) + assert mapped.custom == {'toolUseTokens': 2054} + + def test_reports_grounding_tool_counts_in_custom(self) -> None: + # `grounding_tool_count` as seen live (googleAI, Google Search). + mapped = usage_from_interaction( + Usage.model_validate({ + 'total_tokens': 1011, + 'total_tool_use_tokens': 0, + 'grounding_tool_count': [ + {'type': 'google_search', 'count': 2}, + {'type': 'google_maps', 'count': 1}, + ], + }) + ) + assert mapped.custom == {'googleSearchCount': 2, 'googleMapsCount': 1} + + def test_leaves_custom_unset_without_breakdowns(self) -> None: + mapped = usage_from_interaction(Usage.model_validate({'total_input_tokens': 4, 'total_tokens': 4})) + assert mapped.custom is None + + +class TestWithBasicUsageStats: + request = [ + Message( + role='user', + content=[ + Part.from_text('Describe this'), + Part(media=Media(url='data:image/png;base64,AAAA', content_type='image/png')), + ], + ) + ] + + def test_adds_character_and_media_counts_next_to_the_token_counts(self) -> None: + response = from_interaction_sync( + Interaction.model_validate({ + 'id': 'int-1', + 'status': 'completed', + 'steps': [ + { + 'type': 'model_output', + 'content': [ + {'type': 'text', 'text': 'A cat.'}, + {'type': 'audio', 'mime_type': 'audio/wav', 'data': 'AAAA'}, + ], + } + ], + 'usage': { + 'total_input_tokens': 270, + 'total_output_tokens': 30, + 'total_tokens': 300, + 'input_tokens_by_modality': [ + {'modality': 'text', 'tokens': 12}, + {'modality': 'image', 'tokens': 258}, + ], + }, + }) + ) + result = with_basic_usage_stats(response, self.request) + assert result.usage is not None + # Same keys and values as the JS test (Genkit models dump camelCase). + assert result.usage.model_dump(exclude_none=True) == { + 'inputCharacters': len('Describe this'), + 'inputImages': 1, + 'inputVideos': 0, + 'inputAudioFiles': 0, + 'outputCharacters': len('A cat.'), + 'outputImages': 0, + 'outputVideos': 0, + 'outputAudioFiles': 1, + 'inputTokens': 270, + 'outputTokens': 30, + 'totalTokens': 300, + 'custom': {'inputTextTokens': 12, 'inputImageTokens': 258}, + } + + def test_counts_the_request_even_when_the_api_sent_no_usage(self) -> None: + response = from_interaction_sync(Interaction.model_validate({'id': 'int-1', 'status': 'completed'})) + result = with_basic_usage_stats(response, self.request) + assert result.usage is not None + assert result.usage.input_characters == len('Describe this') + assert result.usage.input_images == 1 + assert result.usage.output_characters == 0 + assert result.usage.input_tokens is None diff --git a/packages/genkit-google-genai/tests/interactions/interactions_errors_test.py b/packages/genkit-google-genai/tests/interactions/interactions_errors_test.py new file mode 100644 index 000000000..ae349da23 --- /dev/null +++ b/packages/genkit-google-genai/tests/interactions/interactions_errors_test.py @@ -0,0 +1,101 @@ +# 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 + +"""Tests for the Interactions error codes (ported from the JS utils tests).""" + +from __future__ import annotations + +import pytest +from genkit_google_genai._interactions._errors import ( + interaction_error_status, + is_interaction_content_block_code, + unwrap_error_body, +) + +CONTENT_BLOCK_CODES = [ + 'safety', + 'recitation', + 'language', + 'prohibited_content', + 'spii', + 'blocklist', + 'image_safety', + 'image_prohibited_content', + 'image_recitation', + 'image_other', + 'content_blocked', + 'jailbreak', + 'model_armor', +] + + +class TestInteractionErrorStatus: + def test_maps_every_known_interactions_error_code(self) -> None: + expected = { + 'service_unavailable': 'UNAVAILABLE', + 'rate_limit_exceeded': 'RESOURCE_EXHAUSTED', + 'quota_exceeded': 'RESOURCE_EXHAUSTED', + 'invalid_request': 'INVALID_ARGUMENT', + 'parameter_unknown': 'INVALID_ARGUMENT', + 'failed_precondition': 'FAILED_PRECONDITION', + 'out_of_range': 'OUT_OF_RANGE', + 'agent_max_token_limit': 'INVALID_ARGUMENT', + 'model_not_found': 'NOT_FOUND', + 'not_found': 'NOT_FOUND', + 'authentication': 'UNAUTHENTICATED', + 'permission_denied': 'PERMISSION_DENIED', + 'already_exists': 'ALREADY_EXISTS', + 'aborted': 'ABORTED', + 'cancelled': 'CANCELLED', + 'deadline_exceeded': 'DEADLINE_EXCEEDED', + 'api_error': 'INTERNAL', + 'unimplemented': 'UNIMPLEMENTED', + 'malformed_function_call': 'ABORTED', + 'unexpected_tool_call': 'ABORTED', + 'no_image': 'ABORTED', + **dict.fromkeys(CONTENT_BLOCK_CODES, 'FAILED_PRECONDITION'), + } + for code, status in expected.items(): + assert interaction_error_status(code) == status, code + + def test_matches_codes_case_insensitively_and_ignores_surrounding_whitespace(self) -> None: + assert interaction_error_status('SERVICE_UNAVAILABLE') == 'UNAVAILABLE' + assert interaction_error_status(' rate_limit_exceeded ') == 'RESOURCE_EXHAUSTED' + + @pytest.mark.parametrize('code', ['weird', '', None, 503, {}]) + def test_returns_none_for_unmappable_codes(self, code: object) -> None: + assert interaction_error_status(code) is None + + +class TestIsInteractionContentBlockCode: + def test_recognizes_content_policy_codes_case_insensitively(self) -> None: + assert is_interaction_content_block_code('safety') + assert is_interaction_content_block_code('MODEL_ARMOR') + assert is_interaction_content_block_code('image_other') + + @pytest.mark.parametrize('code', ['malformed_function_call', 'service_unavailable', None, 400]) + def test_rejects_non_content_policy_codes_and_non_strings(self, code: object) -> None: + assert not is_interaction_content_block_code(code) + + +class TestUnwrapErrorBody: + def test_unwraps_a_one_element_list(self) -> None: + body = {'error': {'code': 400, 'message': 'API key not valid. Please pass a valid API key.'}} + assert unwrap_error_body([body]) == body + + @pytest.mark.parametrize('body', [{'error': {'message': 'x'}}, [], [{'a': 1}, {'b': 2}], 'text', None]) + def test_returns_anything_else_as_is(self, body: object) -> None: + assert unwrap_error_body(body) == body