From 3f16233965978d0af88a989c2c56b23b3e37a770 Mon Sep 17 00:00:00 2001 From: Ingrid Fielker Date: Wed, 11 Nov 2026 13:25:40 -0500 Subject: [PATCH] refactor(py/google-genai)!: own Interactions API types; built-in tool steps round-trip like JS --- .../_interactions/_client.py | 21 +- .../_interactions/_converters.py | 975 +++++++++---- .../_interactions/_errors.py | 34 +- .../_interactions/_types.py | 1205 +++++++++++++++++ .../_models/_interactions_utils.py | 17 +- .../interactions/interactions_client_test.py | 18 +- .../interactions_converters_test.py | 394 +++++- .../interactions/interactions_models_test.py | 22 +- .../interactions/interactions_types_test.py | 134 ++ 9 files changed, 2401 insertions(+), 419 deletions(-) create mode 100644 packages/genkit-google-genai/src/genkit_google_genai/_interactions/_types.py create mode 100644 packages/genkit-google-genai/tests/interactions/interactions_types_test.py 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 2f7bc9246..cf27da2ee 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 @@ -25,8 +25,9 @@ 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._interactions._types import GeminiInteraction, parse_interaction from genkit_google_genai._provider_errors import TRANSPORT_ERRORS, transport_error -from google.genai.interactions import Interaction +from pydantic import ValidationError from genkit import GenkitError from genkit.plugin_api import GENKIT_USER_AGENT, StatusName, loop_local_client, provider_error @@ -86,7 +87,7 @@ async def create_interaction( api_key: str, body: dict[str, object], client_options: ClientOptions | None = None, -) -> Interaction: +) -> GeminiInteraction: """POST /interactions and return the parsed Interaction.""" url = google_ai_url('interactions', client_options=client_options) created = await request( @@ -104,7 +105,7 @@ async def get_interaction( api_key: str, interaction_id: str, client_options: ClientOptions | None = None, -) -> Interaction: +) -> GeminiInteraction: """GET /interactions/{id} and return the parsed Interaction.""" url = google_ai_url(f'interactions/{quote(interaction_id, safe="")}', client_options=client_options) found = await request( @@ -121,7 +122,7 @@ async def cancel_interaction( api_key: str, interaction_id: str, client_options: ClientOptions | None = None, -) -> Interaction: +) -> GeminiInteraction: """POST /interactions/{id}/cancel and return a cancelled Interaction.""" url = google_ai_url(f'interactions/{quote(interaction_id, safe="")}/cancel', client_options=client_options) try: @@ -136,11 +137,11 @@ async def cancel_interaction( ) except GenkitError as error: if error.status == 'CANCELLED': - return Interaction.model_validate({'id': interaction_id, 'status': 'cancelled'}) + return {'id': interaction_id, 'status': 'cancelled'} raise if interaction is None: - return Interaction.model_validate({'id': interaction_id, 'status': 'cancelled'}) - return interaction.model_copy(update={'status': 'cancelled'}) + return {'id': interaction_id, 'status': 'cancelled'} + return {**interaction, 'status': 'cancelled'} def redact(value: str) -> str: @@ -180,7 +181,7 @@ async def request( json_body: dict[str, object] | None = None, allow_empty: bool = False, trace: bool = True, -) -> Interaction | None: +) -> GeminiInteraction | None: """Issue one Interactions HTTP call and parse the Interaction body. With ``experimental_debug_traces`` on the client options (and ``trace``), @@ -213,8 +214,8 @@ async def call(span: SpanContext | None = None) -> object: if body is None: return None try: - return Interaction.model_validate(body) - except Exception as error: + return parse_interaction(body) + except ValidationError as error: raise GenkitError( status='INTERNAL', message=f'Unable to parse Interaction response from {url}: {error}', 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 cd6c053c1..edd625f58 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 @@ -21,55 +21,52 @@ import copy import json import re -from typing import Any, Literal, cast +from collections.abc import Mapping +from typing import Any, Literal, TypeVar, 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 ( +from genkit_google_genai._interactions._types import ( + STEP_ADAPTER, AudioContent, - AudioContentParam, + CodeArguments, CodeExecutionCallStep, - CodeExecutionCallStepParam, CodeExecutionResultStep, - CodeExecutionResultStepParam, Content, - ContentParam, DocumentContent, - DocumentContentParam, + FileSearchCallStep, + FileSearchResultStep, FunctionCallStep, - FunctionCallStepParam, - FunctionParam, FunctionResultStep, - FunctionResultStepParam, - FunctionResultStepResultUnionParam, + GeminiInteraction, + GoogleMapsCallStep, + GoogleMapsResultStep, GoogleSearchCallStep, - GoogleSearchCallStepParam, GoogleSearchResultStep, - GoogleSearchResultStepParam, ImageContent, - ImageContentParam, - Interaction, + InteractionFunctionTool, + McpServerToolCallStep, + McpServerToolResultStep, ModalityTokens, ModelOutputStep, - ModelOutputStepParam, + ProcessingCallStep, + ProcessingResultStep, + QueriesArguments, + Status, Step, - StepParam, TextContent, - TextContentParam, ThoughtStep, - ThoughtStepParam, UnknownContent, + UnknownStep, + UrlContextCallStep, + UrlContextResultStep, + UrlsArguments, Usage, UserInputStep, - UserInputStepParam, VideoContent, - VideoContentParam, ) -from pydantic import BaseModel +from pydantic import BaseModel, TypeAdapter, ValidationError +from typing_extensions import NotRequired, TypedDict from genkit import Failure, FinishReason, GenkitError, Media, Message, ModelResponse, Operation, Part, get_logger from genkit.model import ( @@ -93,14 +90,122 @@ GOOGLE_SEARCH_RESULT = 'googleSearchResult' EXECUTABLE_CODE = 'executableCode' CODE_EXECUTION_RESULT = 'codeExecutionResult' +PROCESSING_CALL = 'processingCall' +PROCESSING_RESULT = 'processingResult' +URL_CONTEXT_CALL = 'urlContextCall' +URL_CONTEXT_RESULT = 'urlContextResult' +FILE_SEARCH_CALL = 'fileSearchCall' +FILE_SEARCH_RESULT = 'fileSearchResult' +GOOGLE_MAPS_CALL = 'googleMapsCall' +GOOGLE_MAPS_RESULT = 'googleMapsResult' +MCP_SERVER_TOOL_CALL = 'mcpServerToolCall' +MCP_SERVER_TOOL_RESULT = 'mcpServerToolResult' UNKNOWN_STEP = 'unknownStep' +UNKNOWN_CONTENT = 'unknownContent' SERVER_FUNCTION_CALL = 'serverFunctionCall' SERVER_FUNCTION_RESULT = 'serverFunctionResult' THOUGHT_CUSTOM = 'thought' # Wire function_result.content is only text/image blocks, not a JSON array. CONTENT_BLOCK_TYPES = frozenset({'text', 'image'}) # The language when a code execution step names none. -CODE_LANGUAGE: Literal['python'] = 'python' +CODE_LANGUAGE = 'python' + + +# Custom parts that stand in for server-side tool steps, read back when the +# history is resent (camelCase keys, like the JS plugin's zod schemas). Only +# the fields the plugin reads; ids default to '' when missing. +class GoogleSearchCallPart(TypedDict): + id: NotRequired[str] + arguments: NotRequired[QueriesArguments] + searchType: NotRequired[str] + + +# `result` is an array of items (e.g. `[{search_suggestions}]`); an object is +# still accepted for parts saved before that was fixed in JS. +class GoogleSearchResultPart(TypedDict): + callId: NotRequired[str] + result: NotRequired[list[dict[str, object]] | dict[str, object]] + isError: NotRequired[bool] + + +class ExecutableCodePart(TypedDict): + code: NotRequired[str] + language: NotRequired[str] + + +class CodeExecutionResultPart(TypedDict): + output: NotRequired[str] + outcome: NotRequired[str] + + +class CallPart(TypedDict): + id: NotRequired[str] + + +class ResultPart(TypedDict): + callId: NotRequired[str] + + +class UrlContextCallPart(TypedDict): + id: NotRequired[str] + arguments: NotRequired[UrlsArguments] + + +class UrlContextResultPart(TypedDict): + callId: NotRequired[str] + result: NotRequired[list[dict[str, object]]] + isError: NotRequired[bool] + + +class ListResultPart(TypedDict): + callId: NotRequired[str] + result: NotRequired[list[dict[str, object]]] + + +class GoogleMapsCallPart(TypedDict): + id: NotRequired[str] + arguments: NotRequired[QueriesArguments] + + +class McpServerToolCallPart(TypedDict): + id: NotRequired[str] + name: NotRequired[str] + serverName: NotRequired[str] + arguments: NotRequired[dict[str, object]] + + +class McpServerToolResultPart(TypedDict): + callId: NotRequired[str] + name: NotRequired[str] + serverName: NotRequired[str] + result: NotRequired[dict[str, object] | str | list[Content]] + + +GOOGLE_SEARCH_CALL_PART: TypeAdapter[GoogleSearchCallPart] = TypeAdapter(GoogleSearchCallPart) +GOOGLE_SEARCH_RESULT_PART: TypeAdapter[GoogleSearchResultPart] = TypeAdapter(GoogleSearchResultPart) +EXECUTABLE_CODE_PART: TypeAdapter[ExecutableCodePart] = TypeAdapter(ExecutableCodePart) +CODE_EXECUTION_RESULT_PART: TypeAdapter[CodeExecutionResultPart] = TypeAdapter(CodeExecutionResultPart) +CALL_PART: TypeAdapter[CallPart] = TypeAdapter(CallPart) +RESULT_PART: TypeAdapter[ResultPart] = TypeAdapter(ResultPart) +URL_CONTEXT_CALL_PART: TypeAdapter[UrlContextCallPart] = TypeAdapter(UrlContextCallPart) +URL_CONTEXT_RESULT_PART: TypeAdapter[UrlContextResultPart] = TypeAdapter(UrlContextResultPart) +LIST_RESULT_PART: TypeAdapter[ListResultPart] = TypeAdapter(ListResultPart) +GOOGLE_MAPS_CALL_PART: TypeAdapter[GoogleMapsCallPart] = TypeAdapter(GoogleMapsCallPart) +MCP_SERVER_TOOL_CALL_PART: TypeAdapter[McpServerToolCallPart] = TypeAdapter(McpServerToolCallPart) +MCP_SERVER_TOOL_RESULT_PART: TypeAdapter[McpServerToolResultPart] = TypeAdapter(McpServerToolResultPart) +CONTENT_LIST_ADAPTER: TypeAdapter[list[Content]] = TypeAdapter(list[Content]) +JSON_OBJECT_ADAPTER: TypeAdapter[dict[str, object]] = TypeAdapter(dict[str, object]) + +_T = TypeVar('_T') + + +def read_as(adapter: TypeAdapter[_T], value: object) -> _T | None: + """``value`` validated as the adapter's type, or None when it doesn't match.""" + try: + return adapter.validate_python(value) + except ValidationError: + return None + FAILED_MESSAGE = 'Interaction failed' # Step errors report a google.rpc code; its position here is that code. @@ -152,22 +257,33 @@ } -def interaction_error_message(interaction: Interaction) -> str | None: +def step_errors(interaction: GeminiInteraction) -> list[Status]: + """The errors on the interaction's ``model_output`` steps.""" + errors: list[Status] = [] + for step in interaction.get('steps') or []: + if isinstance(step, UnknownStep) or step['type'] != 'model_output': + continue + error = step.get('error') + if error is not None: + errors.append(error) + return errors + + +def interaction_error_message(interaction: GeminiInteraction) -> str | None: """Read the failure message a failed Interaction reports. Prefer the top-level errors list when the job died before any output step, then fall back to a step error so callers see the server's reason instead of a generic 'Interaction failed'. """ - for err in interaction.errors or []: - message = getattr(err, 'message', None) + for err in interaction.get('errors') or []: + message = err.get('message') + if message: + return message + for error in step_errors(interaction): + message = error.get('message') if message: - return str(message) - if isinstance(err, dict) and err.get('message'): - return str(err['message']) - for step in interaction.steps or []: - if isinstance(step, ModelOutputStep) and step.error is not None and step.error.message: - return step.error.message + return message return None @@ -202,14 +318,14 @@ def error_from_provider_code(code: object, cause: BaseException) -> GenkitError return error -def first_error(interaction: Interaction) -> tuple[object, str | None]: +def first_error(interaction: GeminiInteraction) -> tuple[str | int | None, 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 + for err in interaction.get('errors') or []: + return err.get('code'), err.get('message') return None, None -def blocked_response(interaction: Interaction) -> ModelResponse | None: +def blocked_response(interaction: GeminiInteraction) -> 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 @@ -227,16 +343,14 @@ def blocked_response(interaction: Interaction) -> ModelResponse | None: ) -def interaction_error(interaction: Interaction, cause: BaseException) -> GenkitError: +def interaction_error(interaction: GeminiInteraction, 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 []: - code = err.get('code') if isinstance(err, dict) else getattr(err, 'code', None) - if error := error_from_provider_code(code, cause): + for err in interaction.get('errors') or []: + if error := error_from_provider_code(err.get('code'), cause): + return error + for step_error in step_errors(interaction): + if error := error_from_provider_code(step_error.get('code'), cause): return error - for step in interaction.steps or []: - if isinstance(step, ModelOutputStep) and step.error is not None: - if error := error_from_provider_code(step.error.code, cause): - return error return provider_error(cause, status='UNKNOWN') @@ -297,9 +411,9 @@ def ensure_tool_ids(messages: list[Message]) -> list[Message]: return new_messages -def to_interaction_tool(tool: ToolDefinition) -> FunctionParam: +def to_interaction_tool(tool: ToolDefinition) -> InteractionFunctionTool: """Convert a Genkit tool definition to an Interactions function tool.""" - func: FunctionParam = { + func: InteractionFunctionTool = { 'type': 'function', 'name': tool.name, } @@ -313,10 +427,10 @@ def to_interaction_tool(tool: ToolDefinition) -> FunctionParam: return func -def to_interaction_content(part: Part) -> ContentParam | None: +def to_interaction_content(part: Part) -> Content | None: """Convert a Genkit part to an Interactions content block.""" if part.text is not None: - text: TextContentParam = {'type': 'text', 'text': part.text} + text: TextContent = {'type': 'text', 'text': part.text} return text if part.media is not None: return to_interaction_media(part) @@ -341,18 +455,18 @@ def is_youtube_url(url: str) -> bool: return host.removeprefix('www.').removeprefix('m.') in YOUTUBE_HOSTS -def video_block(part: Part, *, mime_type: str | None = None) -> VideoContentParam: +def video_block(part: Part, *, mime_type: str | None = None) -> VideoContent: """A video block, with ``metadata['processing']`` (`static` / `agentic`) when the part sets it.""" - video: VideoContentParam = {'type': 'video'} + video: VideoContent = {'type': 'video'} if mime_type: - video['mime_type'] = UnrecognizedStr(mime_type) + video['mime_type'] = mime_type processing = (part.metadata or {}).get('processing') if isinstance(processing, str): - video['processing'] = UnrecognizedStr(processing) + video['processing'] = processing return video -def to_interaction_media(part: Part) -> ContentParam: +def to_interaction_media(part: Part) -> Content: """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 @@ -377,21 +491,18 @@ def to_interaction_media(part: Part) -> ContentParam: youtube = video_block(part) youtube['uri'] = url return youtube - unknown: DocumentContentParam = {'type': 'document', 'uri': url} + unknown: DocumentContent = {'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 + block: ImageContent | AudioContent | VideoContent | DocumentContent if content_type.startswith('image/'): - block = {'type': 'image', 'mime_type': mime_type} + block = {'type': 'image', 'mime_type': content_type} elif content_type.startswith('audio/'): - block = {'type': 'audio', 'mime_type': mime_type} + block = {'type': 'audio', 'mime_type': content_type} elif content_type.startswith('video/'): block = video_block(part, mime_type=content_type) else: - block = {'type': 'document', 'mime_type': mime_type} + block = {'type': 'document', 'mime_type': content_type} # Inline data URLs travel as base64; anything else is a reference the API fetches. if url.startswith('data:'): @@ -436,15 +547,31 @@ def split_system_instruction(messages: list[Message]) -> tuple[str | None, list[ return '\n\n'.join(instructions) or None, turns -def with_signature(step: StepParam, metadata: dict[str, Any]) -> StepParam: - """Carry a thought signature from part metadata back onto its step.""" - signature = metadata.get(THOUGHT_SIGNATURE) - if signature is not None: - cast(dict[str, Any], step)['signature'] = signature - return step +def signature_of(metadata: Mapping[str, object] | None) -> str | None: + """The thought signature stored on a part's metadata, if any.""" + signature = (metadata or {}).get(THOUGHT_SIGNATURE) + return signature if isinstance(signature, str) and signature else None + + +def str_field(payload: Mapping[str, object], *keys: str) -> str: + """The first non-empty string under one of ``keys`` (camelCase or snake_case), else ''.""" + for key in keys: + value = payload.get(key) + if isinstance(value, str) and value: + return value + return '' + + +def without_none(value: object) -> object: + """A copy with ``None``-valued keys dropped at every dict level (JSON ``null`` means unset).""" + if isinstance(value, dict): + return {key: without_none(item) for key, item in value.items() if item is not None} + if isinstance(value, list): + return [without_none(item) for item in value] + return value -def to_function_call_step(request: ToolRequest) -> FunctionCallStepParam: +def to_function_call_step(request: ToolRequest, signature: str | None = None) -> FunctionCallStep: """Compile a Genkit tool request into a function_call step. Arguments on the wire are a JSON object. A scalar like ``'Paris'`` would @@ -452,9 +579,8 @@ def to_function_call_step(request: ToolRequest) -> FunctionCallStepParam: one the caller made. """ dumped = plain(request.input) - if dumped is None: - args: dict[str, Any] = {} - elif not isinstance(dumped, dict): + args = {} if dumped is None else read_as(JSON_OBJECT_ADAPTER, dumped) + if args is None: raise GenkitError( status='INVALID_ARGUMENT', message=( @@ -463,27 +589,25 @@ def to_function_call_step(request: ToolRequest) -> FunctionCallStepParam: "{'city': 'Paris'} rather than passing a bare string." ), ) - else: - args = cast(dict[str, Any], dumped) - return { + step: FunctionCallStep = { 'type': 'function_call', 'name': request.name, 'arguments': args, 'id': request.ref or '', } + if signature: + step['signature'] = signature + return step -def is_content_block_list(value: object) -> bool: - """True when value is a non-empty list of text/image content blocks.""" +def content_block_list(value: object) -> list[Content] | None: + """``value`` as content blocks when it's a non-empty list of text/image blocks, else None.""" if not isinstance(value, list) or not value: - return False - for item in value: - if not isinstance(item, dict): - return False - block = cast(dict[str, object], item) - if block.get('type') not in CONTENT_BLOCK_TYPES: - return False - return True + return None + blocks = read_as(CONTENT_LIST_ADAPTER, value) + if blocks is None or any(block['type'] not in CONTENT_BLOCK_TYPES for block in blocks): + return None + return blocks def metadata_flag(metadata: dict[str, Any] | None, *keys: str) -> object: @@ -499,7 +623,7 @@ def metadata_flag(metadata: dict[str, Any] | None, *keys: str) -> object: def to_function_result_step( response: ToolResponse, metadata: dict[str, Any] | None = None, -) -> FunctionResultStepParam: +) -> FunctionResultStep: """Compile a Genkit tool response into a function_result step. Ordinary JSON arrays (``[1, 2]``) are not multimodal content — they @@ -507,15 +631,18 @@ def to_function_result_step( content. A failed result keeps ``is_error`` so the model sees the miss. """ output = plain(response.output) - if isinstance(output, (str, dict)): - result = cast(FunctionResultStepResultUnionParam, output) - elif is_content_block_list(output): - result = cast(FunctionResultStepResultUnionParam, output) + result: dict[str, object] | str | list[Content] + if isinstance(output, str): + result = output + elif (as_object := read_as(JSON_OBJECT_ADAPTER, output)) is not None: + result = as_object + elif (blocks := content_block_list(output)) is not None: + result = blocks elif output is None: - result = cast(FunctionResultStepResultUnionParam, {}) + result = {} else: - result = cast(FunctionResultStepResultUnionParam, {'result': output}) - step: FunctionResultStepParam = { + result = {'result': output} + step: FunctionResultStep = { 'type': 'function_result', 'name': response.name, 'result': result, @@ -526,138 +653,274 @@ def to_function_result_step( return step -def thought_from_custom(custom: dict[str, Any] | None) -> StepParam | None: +def thought_from_custom(custom: Mapping[str, object] | None) -> Step | None: """Replay a thought step that was stashed on the part, images and all. Rebuilding from ``reasoning`` would drop image summaries and the signature the next turn needs to continue the same thought. """ - if not custom: + thought = read_as(STEP_ADAPTER, (custom or {}).get(THOUGHT_CUSTOM)) + if thought is None or isinstance(thought, UnknownStep) or thought['type'] != 'thought': return None - thought = custom.get(THOUGHT_CUSTOM) - if isinstance(thought, dict) and thought.get('type') == 'thought': - return cast(StepParam, copy.deepcopy(thought)) - return None + return copy.deepcopy(thought) -def to_thought_step(part: Part) -> StepParam: +def to_thought_step(part: Part) -> Step: """Compile a Genkit reasoning part into a thought step.""" original = thought_from_custom(part.custom) if original is not None: return original - thought: ThoughtStepParam = { + thought: ThoughtStep = { 'type': 'thought', 'summary': [{'type': 'text', 'text': part.reasoning or ''}], } - return with_signature(thought, part.metadata or {}) + if signature := signature_of(part.metadata): + thought['signature'] = signature + return thought -def to_server_function_call_step(payload: dict[str, Any]) -> FunctionCallStepParam: +def to_server_function_call_step(payload: Mapping[str, object], signature: str | None) -> FunctionCallStep: """Replay a server-executed function_call that was stashed as custom.""" - raw_args = payload.get('arguments') - return { + step: FunctionCallStep = { 'type': 'function_call', - 'name': payload.get('name') or '', - 'arguments': cast(dict[str, Any], raw_args) if isinstance(raw_args, dict) else {}, - 'id': payload.get('id') or '', + 'name': str_field(payload, 'name'), + 'arguments': read_as(JSON_OBJECT_ADAPTER, payload.get('arguments')) or {}, + 'id': str_field(payload, 'id'), } + if signature: + step['signature'] = signature + return step + + +def function_result_value(value: object) -> dict[str, object] | str | list[Content] | None: + """A stored function result as one of the wire shapes (object, string or content blocks), else None.""" + if isinstance(value, str): + return value + as_object = read_as(JSON_OBJECT_ADAPTER, value) + if as_object is not None: + return as_object + return read_as(CONTENT_LIST_ADAPTER, value) -def to_server_function_result_step(payload: dict[str, Any]) -> FunctionResultStepParam: - """Replay a function_result that was stashed as custom, including is_error.""" - step: FunctionResultStepParam = { +def to_server_function_result_step(payload: Mapping[str, object]) -> FunctionResultStep: + """Replay a function_result that was stashed as custom. + + ``is_error`` is sent back as stored, ``False`` included (like the other + tool results); it's left out only when the server didn't send it. + """ + step: FunctionResultStep = { 'type': 'function_result', - 'name': payload.get('name') or '', - 'result': cast(FunctionResultStepResultUnionParam, payload.get('result')), - 'call_id': payload.get('call_id') or payload.get('callId') or '', + 'name': str_field(payload, 'name'), + 'call_id': str_field(payload, 'call_id', 'callId'), } - if payload.get('is_error') or payload.get('isError'): - step['is_error'] = True + result = function_result_value(payload.get('result')) + if result is not None: + step['result'] = result + for key in ('is_error', 'isError'): + is_error = payload.get(key) + if isinstance(is_error, bool): + step['is_error'] = is_error + break return step -def to_server_tool_step(custom: dict[str, Any], metadata: dict[str, Any]) -> StepParam | None: +def to_server_tool_step(custom: Mapping[str, object], metadata: Mapping[str, object]) -> Step | None: """Compile the custom parts that stand in for Google-side tool activity. Search and code execution run on Google's side, so Genkit has no first-class - part for them and we round-trip them through custom parts instead. + part for them and we round-trip them through custom parts instead. Fields + the part doesn't have are left out, as in JS. """ - if GOOGLE_SEARCH_CALL in custom: - call = custom[GOOGLE_SEARCH_CALL] - search_call: GoogleSearchCallStepParam = { - 'type': 'google_search_call', - 'id': call.get('id', ''), - 'arguments': call.get('arguments'), - } + signature = signature_of(metadata) + if (search := read_as(GOOGLE_SEARCH_CALL_PART, custom.get(GOOGLE_SEARCH_CALL))) is not None: + search_call: GoogleSearchCallStep = {'type': 'google_search_call', 'id': search.get('id', '')} + if 'arguments' in search: + search_call['arguments'] = search['arguments'] + if search_type := search.get('searchType'): + search_call['search_type'] = search_type + if signature: + search_call['signature'] = signature return search_call - if GOOGLE_SEARCH_RESULT in custom: - result = custom[GOOGLE_SEARCH_RESULT] - search_result: GoogleSearchResultStepParam = { - 'type': 'google_search_result', - 'call_id': result.get(CALL_ID, ''), - 'result': result.get('result'), - } + if (found := read_as(GOOGLE_SEARCH_RESULT_PART, custom.get(GOOGLE_SEARCH_RESULT))) is not None: + search_result: GoogleSearchResultStep = {'type': 'google_search_result', 'call_id': found.get('callId', '')} + if 'result' in found: + search_result['result'] = found['result'] + if 'isError' in found: + search_result['is_error'] = found['isError'] + if signature: + search_result['signature'] = signature return search_result - if EXECUTABLE_CODE in custom: - code = custom[EXECUTABLE_CODE] - stored_language = code.get('language') + if (code := read_as(EXECUTABLE_CODE_PART, custom.get(EXECUTABLE_CODE))) is not None: # 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 = { + # say 'PYTHON', which it rejects (400, seen live). + arguments: CodeArguments = {'language': code.get('language', '').lower() or CODE_LANGUAGE} + if 'code' in code: + arguments = {'code': code['code'], **arguments} + code_call: CodeExecutionCallStep = { 'type': 'code_execution_call', - 'id': metadata.get(CALL_ID, ''), - 'arguments': {'code': code.get('code'), 'language': language}, + 'id': str_field(metadata, CALL_ID), + 'arguments': arguments, } + if signature: + code_call['signature'] = signature return code_call - if CODE_EXECUTION_RESULT in custom: - code_result: CodeExecutionResultStepParam = { + if (output := read_as(CODE_EXECUTION_RESULT_PART, custom.get(CODE_EXECUTION_RESULT))) is not None: + code_result: CodeExecutionResultStep = { 'type': 'code_execution_result', - 'call_id': metadata.get(CALL_ID, ''), - 'result': custom[CODE_EXECUTION_RESULT].get('output'), + 'call_id': str_field(metadata, CALL_ID), } + if 'output' in output: + code_result['result'] = output['output'] + if signature: + code_result['signature'] = signature return code_result + return to_processing_step(custom, signature) or to_built_in_tool_step(custom, signature) + + +def to_processing_step(custom: Mapping[str, object], signature: str | None) -> Step | None: + """Rebuild an agentic video ``processing_call`` / ``processing_result`` step, as it came back.""" + if (call := read_as(CALL_PART, custom.get(PROCESSING_CALL))) is not None: + processing_call: ProcessingCallStep = {'type': 'processing_call', 'id': call.get('id', '')} + if signature: + processing_call['signature'] = signature + return processing_call + if (result := read_as(RESULT_PART, custom.get(PROCESSING_RESULT))) is not None: + processing_result: ProcessingResultStep = {'type': 'processing_result', 'call_id': result.get('callId', '')} + if signature: + processing_result['signature'] = signature + return processing_result return None -def to_standalone_step(part: Part) -> StepParam | None: +def to_built_in_tool_step(custom: Mapping[str, object], signature: str | None) -> Step | None: + """Rebuild a server-side built-in tool step (url context, file search, Google Maps, MCP server). + + The reverse of ``from_built_in_tool_step``: the step goes back in the + history with its signature, and fields the part doesn't have are left + out (JS toBuiltInToolStep). + """ + if (url_call := read_as(URL_CONTEXT_CALL_PART, custom.get(URL_CONTEXT_CALL))) is not None: + url_context_call: UrlContextCallStep = {'type': 'url_context_call', 'id': url_call.get('id', '')} + if 'arguments' in url_call: + url_context_call['arguments'] = url_call['arguments'] + if signature: + url_context_call['signature'] = signature + return url_context_call + if (url_result := read_as(URL_CONTEXT_RESULT_PART, custom.get(URL_CONTEXT_RESULT))) is not None: + url_context_result: UrlContextResultStep = { + 'type': 'url_context_result', + 'call_id': url_result.get('callId', ''), + } + if 'result' in url_result: + url_context_result['result'] = url_result['result'] + if 'isError' in url_result: + url_context_result['is_error'] = url_result['isError'] + if signature: + url_context_result['signature'] = signature + return url_context_result + if (file_call := read_as(CALL_PART, custom.get(FILE_SEARCH_CALL))) is not None: + file_search_call: FileSearchCallStep = {'type': 'file_search_call', 'id': file_call.get('id', '')} + if signature: + file_search_call['signature'] = signature + return file_search_call + if (file_result := read_as(LIST_RESULT_PART, custom.get(FILE_SEARCH_RESULT))) is not None: + file_search_result: FileSearchResultStep = { + 'type': 'file_search_result', + 'call_id': file_result.get('callId', ''), + } + if 'result' in file_result: + file_search_result['result'] = file_result['result'] + if signature: + file_search_result['signature'] = signature + return file_search_result + if (maps_call := read_as(GOOGLE_MAPS_CALL_PART, custom.get(GOOGLE_MAPS_CALL))) is not None: + google_maps_call: GoogleMapsCallStep = {'type': 'google_maps_call', 'id': maps_call.get('id', '')} + if 'arguments' in maps_call: + google_maps_call['arguments'] = maps_call['arguments'] + if signature: + google_maps_call['signature'] = signature + return google_maps_call + if (maps_result := read_as(LIST_RESULT_PART, custom.get(GOOGLE_MAPS_RESULT))) is not None: + google_maps_result: GoogleMapsResultStep = { + 'type': 'google_maps_result', + 'call_id': maps_result.get('callId', ''), + } + if 'result' in maps_result: + google_maps_result['result'] = maps_result['result'] + if signature: + google_maps_result['signature'] = signature + return google_maps_result + return to_mcp_server_tool_step(custom) + + +def to_mcp_server_tool_step(custom: Mapping[str, object]) -> Step | None: + """Rebuild an MCP server tool call or result step (MCP steps have no signature in the spec).""" + if (mcp_call := read_as(MCP_SERVER_TOOL_CALL_PART, custom.get(MCP_SERVER_TOOL_CALL))) is not None: + call_step: McpServerToolCallStep = {'type': 'mcp_server_tool_call', 'id': mcp_call.get('id', '')} + if name := mcp_call.get('name'): + call_step['name'] = name + if server_name := mcp_call.get('serverName'): + call_step['server_name'] = server_name + if 'arguments' in mcp_call: + call_step['arguments'] = mcp_call['arguments'] + return call_step + if (mcp_result := read_as(MCP_SERVER_TOOL_RESULT_PART, custom.get(MCP_SERVER_TOOL_RESULT))) is not None: + result_step: McpServerToolResultStep = { + 'type': 'mcp_server_tool_result', + 'call_id': mcp_result.get('callId', ''), + } + if name := mcp_result.get('name'): + result_step['name'] = name + if server_name := mcp_result.get('serverName'): + result_step['server_name'] = server_name + if 'result' in mcp_result: + result_step['result'] = mcp_result['result'] + return result_step + return None + + +def unknown_step_from_custom(custom: Mapping[str, object]) -> Step | None: + """Resend a step stored as ``unknownStep`` as it came back. + + ``None`` values are dropped first: parts saved by older plugin versions + can hold fields the SDK filled in with ``None`` that the server never sent. + """ + return read_as(STEP_ADAPTER, without_none(custom.get(UNKNOWN_STEP))) + + +def to_standalone_step(part: Part) -> Step | None: """Return the step a part compiles to on its own, or None if it is inline content.""" + signature = signature_of(part.metadata) if part.tool_request: - return with_signature(to_function_call_step(part.tool_request), part.metadata or {}) + return to_function_call_step(part.tool_request, signature) if part.tool_response: return to_function_result_step(part.tool_response, part.metadata) if part.reasoning is not None: return to_thought_step(part) if part.custom is not None: - custom = part.custom or {} + custom = part.custom original_thought = thought_from_custom(custom) if original_thought is not None: return original_thought - unknown = custom.get(UNKNOWN_STEP) - if isinstance(unknown, dict): - return cast(StepParam, copy.deepcopy(unknown)) - metadata = part.metadata or {} - server_call = custom.get(SERVER_FUNCTION_CALL) - if isinstance(server_call, dict): - return with_signature(to_server_function_call_step(server_call), metadata) - server_result = custom.get(SERVER_FUNCTION_RESULT) - if isinstance(server_result, dict): + unknown = unknown_step_from_custom(custom) + if unknown is not None: + return unknown + server_call = read_as(JSON_OBJECT_ADAPTER, custom.get(SERVER_FUNCTION_CALL)) + if server_call is not None: + return to_server_function_call_step(server_call, signature) + server_result = read_as(JSON_OBJECT_ADAPTER, custom.get(SERVER_FUNCTION_RESULT)) + if server_result is not None: return to_server_function_result_step(server_result) - step = to_server_tool_step(custom, metadata) - return with_signature(step, metadata) if step is not None else None + return to_server_tool_step(custom, part.metadata or {}) return None -def to_content_step(role: InteractionRole, content: list[ContentParam]) -> StepParam: +def to_content_step(role: InteractionRole, content: list[Content]) -> Step: """Wrap a turn's inline content in the step for whoever produced it.""" if role == 'model': - model_step: ModelOutputStepParam = {'type': 'model_output', 'content': content} + model_step: ModelOutputStep = {'type': 'model_output', 'content': content} return model_step - user_step: UserInputStepParam = {'type': 'user_input', 'content': content} + user_step: UserInputStep = {'type': 'user_input', 'content': content} return user_step @@ -697,7 +960,7 @@ def ensure_code_execution_ids(messages: list[Message]) -> list[Message]: return result -def to_interaction_steps(messages: list[Message]) -> list[StepParam]: +def to_interaction_steps(messages: list[Message]) -> list[Step]: """Convert Genkit messages to Interactions API steps. Text and media collapse into a content step, but tool calls, thoughts, @@ -706,10 +969,10 @@ def to_interaction_steps(messages: list[Message]) -> list[StepParam]: thought sitting between two sentences must not jump the first sentence to the end of the turn. """ - steps: list[StepParam] = [] + steps: list[Step] = [] for message in ensure_code_execution_ids(messages): role = to_interaction_role(message.role) - inline: list[ContentParam] = [] + inline: list[Content] = [] for part in message.content: step = to_standalone_step(part) @@ -745,55 +1008,56 @@ def plain(value: object) -> object: return value -def server_tool_part(key: str, payload: dict[str, Any], *, signature: str | None, call_id: str | None = None) -> Part: +def server_tool_part( + key: str, payload: Mapping[str, object], *, signature: str | None, call_id: str | None = None +) -> Part: """Wrap Google-side tool activity in the custom part Genkit round-trips.""" - part = Part.from_custom({key: payload}, metadata={CALL_ID: call_id} if call_id else None) + part = Part.from_custom({key: dict(payload)}, metadata={CALL_ID: call_id} if call_id else None) return with_metadata(part, THOUGHT_SIGNATURE, signature) def from_google_search_call(step: GoogleSearchCallStep) -> Part: - """Convert a google_search_call step to a Genkit custom part.""" - return server_tool_part( - GOOGLE_SEARCH_CALL, - {'id': step.id, 'arguments': plain(step.arguments)}, - signature=step.signature, - ) + """Convert a google_search_call step to a Genkit custom part (fields left out when missing, as in JS).""" + payload: dict[str, object] = {'id': step.get('id', '')} + if 'arguments' in step: + payload['arguments'] = step['arguments'] + if search_type := step.get('search_type'): + payload['searchType'] = search_type + return server_tool_part(GOOGLE_SEARCH_CALL, payload, signature=step.get('signature')) def from_google_search_result(step: GoogleSearchResultStep) -> Part: - """Convert a google_search_result step to a Genkit custom part.""" - return server_tool_part( - GOOGLE_SEARCH_RESULT, - {CALL_ID: step.call_id, 'result': plain(step.result or [])}, - signature=step.signature, - ) + """Convert a google_search_result step to a Genkit custom part (fields left out when missing, as in JS).""" + payload: dict[str, object] = {CALL_ID: step.get('call_id', '')} + if 'result' in step: + payload['result'] = step['result'] + if 'is_error' in step: + payload['isError'] = step['is_error'] + return server_tool_part(GOOGLE_SEARCH_RESULT, payload, signature=step.get('signature')) def from_code_execution_call(step: CodeExecutionCallStep) -> Part: """Convert a code_execution_call step to a Genkit custom part.""" - arguments = step.arguments + arguments = step.get('arguments') or {} return server_tool_part( EXECUTABLE_CODE, - { - 'code': arguments.code if arguments else None, - 'language': (arguments.language if arguments else None) or CODE_LANGUAGE, - }, - signature=step.signature, - call_id=step.id, + {'code': arguments.get('code'), 'language': arguments.get('language') or CODE_LANGUAGE}, + signature=step.get('signature'), + call_id=step.get('id'), ) def from_code_execution_result(step: CodeExecutionResultStep) -> Part: """Convert a code_execution_result step to a Genkit custom part.""" - result = step.result + result = step.get('result') return server_tool_part( CODE_EXECUTION_RESULT, { 'output': result if isinstance(result, str) else json.dumps(result), 'outcome': 'OUTCOME_OK', }, - signature=step.signature, - call_id=step.call_id, + signature=step.get('signature'), + call_id=step.get('call_id'), ) @@ -801,25 +1065,25 @@ def from_function_call_step(step: FunctionCallStep) -> Part: """Convert a pending client function_call step to a Genkit tool request part.""" part = Part( tool_request=ToolRequest( - name=step.name or '', - input=plain(step.arguments) if step.arguments is not None else {}, - ref=step.id, + name=step.get('name', ''), + input=step.get('arguments', {}), + ref=step.get('id'), ) ) - return with_metadata(part, THOUGHT_SIGNATURE, getattr(step, 'signature', None)) + return with_metadata(part, THOUGHT_SIGNATURE, step.get('signature')) def from_server_function_call_step(step: FunctionCallStep) -> Part: """Stash an already-resolved or sandbox function_call as custom so Genkit's tool loop skips it.""" - payload: dict[str, Any] = { - 'id': step.id, - 'name': step.name or '', - 'arguments': plain(step.arguments) if step.arguments is not None else {}, + payload: dict[str, object] = { + 'id': step.get('id'), + 'name': step.get('name', ''), + 'arguments': step.get('arguments', {}), } return with_metadata( Part.from_custom({SERVER_FUNCTION_CALL: payload}), THOUGHT_SIGNATURE, - getattr(step, 'signature', None), + step.get('signature'), ) @@ -829,14 +1093,98 @@ def from_function_result_step(step: FunctionResultStep) -> Part: The API echoes the client's own tool result back on the model tape. Putting that on a ToolResponsePart would send it again next turn. """ - return Part.from_custom({ - SERVER_FUNCTION_RESULT: { - 'name': step.name or '', - 'result': plain(step.result), - 'call_id': step.call_id, - 'is_error': step.is_error, - } - }) + payload: dict[str, object] = { + 'name': step.get('name', ''), + 'result': step.get('result'), + 'call_id': step.get('call_id'), + } + # Kept only when the server sent it, so it's resent the same way. + if 'is_error' in step: + payload['is_error'] = step['is_error'] + return Part.from_custom({SERVER_FUNCTION_RESULT: payload}) + + +def from_processing_step(step: ProcessingCallStep | ProcessingResultStep) -> Part: + """Convert an agentic video processing step to a custom part with its signature (JS).""" + if step['type'] == 'processing_call': + part = Part.from_custom({PROCESSING_CALL: {'id': step.get('id', '')}}) + else: + part = Part.from_custom({PROCESSING_RESULT: {CALL_ID: step.get('call_id', '')}}) + return with_metadata(part, THOUGHT_SIGNATURE, step.get('signature')) + + +def add_mcp_names(payload: dict[str, object], step: McpServerToolCallStep | McpServerToolResultStep) -> None: + """Copy an MCP step's tool and server names onto its custom part, when set.""" + if name := step.get('name'): + payload['name'] = name + if server_name := step.get('server_name'): + payload['serverName'] = server_name + + +def from_built_in_tool_step( + step: UrlContextCallStep + | UrlContextResultStep + | FileSearchCallStep + | FileSearchResultStep + | GoogleMapsCallStep + | GoogleMapsResultStep + | McpServerToolCallStep + | McpServerToolResultStep, +) -> Part: + """Convert a server-side built-in tool step to a custom part (JS fromBuiltInToolStep). + + The signature goes in ``metadata.thoughtSignature``; fields the server + left out are left out. ``to_built_in_tool_step`` turns the part back into + the step when the history is resent. Never a ``toolRequest``: the server + ran the tool, so there's nothing for Genkit to run. + """ + payload: dict[str, object] = {} + # MCP steps have no signature in the spec. + if step['type'] == 'mcp_server_tool_call': + payload['id'] = step.get('id', '') + add_mcp_names(payload, step) + if 'arguments' in step: + payload['arguments'] = step['arguments'] + return Part.from_custom({MCP_SERVER_TOOL_CALL: payload}) + if step['type'] == 'mcp_server_tool_result': + payload[CALL_ID] = step.get('call_id', '') + add_mcp_names(payload, step) + if 'result' in step: + payload['result'] = step['result'] + return Part.from_custom({MCP_SERVER_TOOL_RESULT: payload}) + + signature = step.get('signature') + if step['type'] == 'url_context_call': + key = URL_CONTEXT_CALL + payload['id'] = step.get('id', '') + if 'arguments' in step: + payload['arguments'] = step['arguments'] + elif step['type'] == 'url_context_result': + key = URL_CONTEXT_RESULT + payload[CALL_ID] = step.get('call_id', '') + if 'result' in step: + payload['result'] = step['result'] + if 'is_error' in step: + payload['isError'] = step['is_error'] + elif step['type'] == 'file_search_call': + key = FILE_SEARCH_CALL + payload['id'] = step.get('id', '') + elif step['type'] == 'file_search_result': + key = FILE_SEARCH_RESULT + payload[CALL_ID] = step.get('call_id', '') + if 'result' in step: + payload['result'] = step['result'] + elif step['type'] == 'google_maps_call': + key = GOOGLE_MAPS_CALL + payload['id'] = step.get('id', '') + if 'arguments' in step: + payload['arguments'] = step['arguments'] + else: + key = GOOGLE_MAPS_RESULT + payload[CALL_ID] = step.get('call_id', '') + if 'result' in step: + payload['result'] = step['result'] + return with_metadata(Part.from_custom({key: payload}), THOUGHT_SIGNATURE, signature) def interaction_media_mime_type(content: ImageContent | AudioContent | DocumentContent | VideoContent) -> str | None: @@ -850,53 +1198,62 @@ def interaction_media_mime_type(content: ImageContent | AudioContent | DocumentC 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}' + mime_type = content.get('mime_type') + data = content.get('data') + if mime_type or content['type'] != 'audio' or not data: + return mime_type + sample_rate = content.get('sample_rate') or 24000 + channels = content.get('channels') or 1 + return f'audio/l16; rate={sample_rate}; channels={channels}' 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 mime_type: - url = f'data:{mime_type};base64,{content.data}' + url = content.get('uri') + data = content.get('data') + if data and mime_type: + url = f'data:{mime_type};base64,{data}' return Part(media=Media(url=url or '', content_type=mime_type)) def from_text_content(content: TextContent) -> Part: """Convert wire text content to a Genkit text part.""" # Empty annotations still show up in metadata so round-trips stay stable. - return Part.from_text(content.text or '', metadata={'annotations': plain(content.annotations)}) + return Part.from_text(content.get('text', ''), metadata={'annotations': content.get('annotations')}) def from_visual_content(content: ImageContent | VideoContent) -> Part: """Convert wire image or video content, keeping the resolution it came back at.""" - return with_metadata(from_media_content(content), 'resolution', content.resolution) + return with_metadata(from_media_content(content), 'resolution', content.get('resolution')) def from_thought_step(step: ThoughtStep) -> Part: """Convert a thought step to a Genkit reasoning part.""" - summary = step.summary or [] - reasoning = '\n'.join(item.text or '' if isinstance(item, TextContent) else '[Image]' for item in summary) - return Part( - reasoning=reasoning, - metadata={THOUGHT_SIGNATURE: step.signature}, - custom={THOUGHT_CUSTOM: step.model_dump(mode='python')}, + reasoning = '\n'.join( + item.get('text', '') if not isinstance(item, UnknownContent) and item['type'] == 'text' else '[Image]' + for item in step.get('summary') or [] ) + # The signature can come in a step of its own (summary and signature are + # sometimes separate steps), so it's set only when this step has one. + part = Part(reasoning=reasoning, custom={THOUGHT_CUSTOM: dict(step)}) + return with_metadata(part, THOUGHT_SIGNATURE, step.get('signature')) def from_interaction_content(content: Content) -> Part: - """Convert an Interactions content block back to a Genkit part.""" - if isinstance(content, TextContent): - return from_text_content(content) - if isinstance(content, (ImageContent, VideoContent)): - return from_visual_content(content) - if isinstance(content, (AudioContent, DocumentContent)): - return from_media_content(content) - if isinstance(content, UnknownContent): - return Part.from_custom({'unknownContent': content.model_dump(mode='python')}) - return Part.from_custom({'unknownContent': content}) + """Convert an Interactions content block back to a Genkit part. + + Thought and function call/result blocks (content, not steps) and unknown + types come back as a custom ``unknownContent`` part. + """ + if not isinstance(content, UnknownContent): + if content['type'] == 'text': + return from_text_content(content) + if content['type'] == 'image' or content['type'] == 'video': + return from_visual_content(content) + if content['type'] == 'audio' or content['type'] == 'document': + return from_media_content(content) + return Part.from_custom({UNKNOWN_CONTENT: dict(content)}) def get_pending_function_call_ids(steps: list[Step], status: str | None) -> set[str]: @@ -909,46 +1266,64 @@ def get_pending_function_call_ids(steps: list[Step], status: str | None) -> set[ """ if status != 'requires_action': return set() - resolved = {step.call_id for step in steps if isinstance(step, FunctionResultStep) and step.call_id} - return {step.id for step in steps if isinstance(step, FunctionCallStep) and step.id and step.id not in resolved} + resolved: set[str] = set() + calls: list[str] = [] + for step in steps: + if isinstance(step, UnknownStep): + continue + if step['type'] == 'function_result' and (call_id := step.get('call_id')): + resolved.add(call_id) + elif step['type'] == 'function_call' and (call := step.get('id')): + calls.append(call) + return {call for call in calls if call not in resolved} + + +def is_pending_call(step: Step, pending_ids: set[str]) -> bool: + """True for a function_call step waiting for the client (see ``get_pending_function_call_ids``).""" + if isinstance(step, UnknownStep) or step['type'] != 'function_call': + return False + call_id = step.get('id') + return bool(call_id) and call_id in pending_ids def from_interaction_step(step: Step, *, is_pending: bool = False) -> list[Part]: """Convert an Interactions step to Genkit parts.""" - if isinstance(step, ModelOutputStep): - return [from_interaction_content(content) for content in (step.content or [])] - if isinstance(step, UserInputStep): + if isinstance(step, UnknownStep): + return [Part.from_custom({UNKNOWN_STEP: dict(step)})] + if step['type'] == 'model_output': + return [from_interaction_content(content) for content in step.get('content') or []] + if step['type'] == 'user_input': # The API echoes our prompt back; including it would duplicate the input. return [] - if isinstance(step, GoogleSearchCallStep): + if step['type'] == 'google_search_call': return [from_google_search_call(step)] - if isinstance(step, GoogleSearchResultStep): + if step['type'] == 'google_search_result': return [from_google_search_result(step)] - if isinstance(step, CodeExecutionCallStep): + if step['type'] == 'code_execution_call': return [from_code_execution_call(step)] - if isinstance(step, CodeExecutionResultStep): + if step['type'] == 'code_execution_result': return [from_code_execution_result(step)] - if isinstance(step, ThoughtStep): + if step['type'] == 'thought': return [from_thought_step(step)] - if isinstance(step, FunctionCallStep): + if step['type'] == 'function_call': return [from_function_call_step(step)] if is_pending else [from_server_function_call_step(step)] - if isinstance(step, FunctionResultStep): + if step['type'] == 'function_result': return [from_function_result_step(step)] - if isinstance(step, BaseModel): - return [Part.from_custom({UNKNOWN_STEP: step.model_dump(mode='python')})] - return [Part.from_custom({UNKNOWN_STEP: step})] + if step['type'] == 'processing_call' or step['type'] == 'processing_result': + return [from_processing_step(step)] + return [from_built_in_tool_step(step)] -def interaction_message_metadata(interaction: Interaction) -> dict[str, Any] | None: +def interaction_message_metadata(interaction: GeminiInteraction) -> dict[str, Any] | None: """Build message.metadata fields that identify the source Interaction.""" metadata: dict[str, Any] = {} - if interaction.id: - metadata['interactionId'] = interaction.id - if interaction.environment_id: - metadata['environmentId'] = interaction.environment_id - if interaction.status: + if interaction_id := interaction.get('id'): + metadata['interactionId'] = interaction_id + if environment_id := interaction.get('environment_id'): + metadata['environmentId'] = environment_id + if status := interaction.get('status'): # Preserve the wire status when finish_reason is a coarser Genkit enum. - metadata['interactionStatus'] = interaction.status + metadata['interactionStatus'] = status return metadata or None @@ -966,32 +1341,36 @@ def usage_from_interaction(usage: Usage) -> GenerationUsage: 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, - total_tokens=usage.total_tokens, - cached_content_tokens=usage.total_cached_tokens, - thoughts_tokens=usage.total_thought_tokens, + input_tokens=usage.get('total_input_tokens'), + output_tokens=usage.get('total_output_tokens'), + total_tokens=usage.get('total_tokens'), + cached_content_tokens=usage.get('total_cached_tokens'), + thoughts_tokens=usage.get('total_thought_tokens'), ) # 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) + modality = item.get('modality') + tokens = item.get('tokens') + if modality and isinstance(tokens, int): + key = f'{direction}{modality[:1].upper()}{modality[1:]}Tokens' + custom[key] = custom.get(key, 0) + tokens + + add_modality_tokens('input', usage.get('input_tokens_by_modality')) + add_modality_tokens('output', usage.get('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 + if tool_use_tokens := usage.get('total_tool_use_tokens'): + custom['toolUseTokens'] = 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 + for tool_count in usage.get('grounding_tool_count') or []: + tool = tool_count.get('type') + count = tool_count.get('count') + if tool and isinstance(count, int): + key = f'{snake_to_camel(tool)}Count' + custom[key] = custom.get(key, 0) + count if custom: response_usage.custom = custom return response_usage @@ -1025,36 +1404,36 @@ def parts_from_steps(steps: list[Step], *, status: str | None = None) -> list[Pa return [ part for step in steps - for part in from_interaction_step( - step, - is_pending=isinstance(step, FunctionCallStep) and bool(step.id) and step.id in pending_ids, - ) + for part in from_interaction_step(step, is_pending=is_pending_call(step, pending_ids)) if part.model_dump(exclude_none=True) ] def model_response( - interaction: Interaction, + interaction: GeminiInteraction, *, content: list[Part], finish_reason: FinishReason, finish_message: str | None = None, ) -> ModelResponse: - """Build a ModelResponse that carries the raw interaction alongside its parts.""" - dumped = interaction.model_dump(mode='python') + """Build a ModelResponse that carries the raw interaction (as the server sent it) alongside its parts. + + Only ``raw``: Genkit deprecates the response-level ``custom`` in favor of + ``raw``. + """ response = ModelResponse.model_construct( finish_reason=finish_reason, finish_message=finish_message, message=Message(role='model', content=content, metadata=interaction_message_metadata(interaction)), - custom=dumped, - raw=dumped, + raw=dict(interaction), ) - if interaction.usage is not None: - response.usage = usage_from_interaction(interaction.usage) + usage = interaction.get('usage') + if usage is not None: + response.usage = usage_from_interaction(usage) return response -def cancelled_response(interaction: Interaction) -> ModelResponse: +def cancelled_response(interaction: GeminiInteraction) -> ModelResponse: """Build the ModelResponse for a cancelled Interaction.""" return model_response( interaction, @@ -1065,29 +1444,29 @@ def cancelled_response(interaction: Interaction) -> ModelResponse: def steps_response( - interaction: Interaction, + interaction: GeminiInteraction, *, finish_reason: FinishReason, finish_message: str | None = None, ) -> ModelResponse | None: """Build a ModelResponse from interaction steps, or None when there are none.""" - steps = list(interaction.steps or []) + steps = list(interaction.get('steps') or []) if not steps: return None return model_response( interaction, - content=parts_from_steps(steps, status=interaction.status), + content=parts_from_steps(steps, status=interaction.get('status')), finish_reason=finish_reason, finish_message=finish_message, ) -def completed_response(interaction: Interaction) -> ModelResponse | None: +def completed_response(interaction: GeminiInteraction) -> ModelResponse | None: """Build the ModelResponse for a completed Interaction, if it has steps.""" return steps_response(interaction, finish_reason=FinishReason.STOP) -def from_interaction_sync(interaction: Interaction) -> ModelResponse: +def from_interaction_sync(interaction: GeminiInteraction) -> ModelResponse: """Convert a finished or paused interaction to a synchronous model response. ``requires_action`` is a deliberate pause for client function calling, so @@ -1101,7 +1480,7 @@ def from_interaction_sync(interaction: Interaction) -> ModelResponse: content-policy block, which returns a response with finish_reason 'blocked'. """ - status = interaction.status + status = interaction.get('status') if status == 'failed': if (blocked := blocked_response(interaction)) is not None: return blocked @@ -1114,7 +1493,7 @@ def from_interaction_sync(interaction: Interaction) -> ModelResponse: status='FAILED_PRECONDITION', message=f'Interaction is still running (status={status!r})', ) - if partial := PARTIAL_TERMINAL_STATUSES.get(cast(str, status)): + if status is not None and (partial := PARTIAL_TERMINAL_STATUSES.get(status)): finish_reason, message = partial response = steps_response(interaction, finish_reason=finish_reason, finish_message=message) if response is None: @@ -1127,11 +1506,11 @@ def from_interaction_sync(interaction: Interaction) -> ModelResponse: raise ValueError(f'Unknown interaction status: {status!r}') -def from_interaction(interaction: Interaction) -> Operation: +def from_interaction(interaction: GeminiInteraction) -> Operation: """Convert an interaction poll result to a Genkit operation.""" - op = Operation.model_construct(id=interaction.id or '') + op = Operation.model_construct(id=interaction.get('id') or '') - status = interaction.status + status = interaction.get('status') if status in ('in_progress', 'queued'): # Keep polling — still running or waiting on the server. op.done = False @@ -1143,7 +1522,7 @@ def from_interaction(interaction: Interaction) -> Operation: op.output = completed_response(interaction) or model_response( interaction, content=[], finish_reason=FinishReason.STOP ) - elif partial := PARTIAL_TERMINAL_STATUSES.get(cast(str, status)): + elif status is not None and (partial := PARTIAL_TERMINAL_STATUSES.get(status)): # Halted for length or budget. Prefer whatever landed over a bare error. finish_reason, message = partial op.done = True 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 index efeab6636..dd4b5e07b 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_errors.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_errors.py @@ -18,7 +18,8 @@ from __future__ import annotations -from pydantic import BaseModel, ConfigDict, ValidationError +from genkit_google_genai._interactions._types import API_ERROR_BODY_ADAPTER +from pydantic import ValidationError from genkit.plugin_api import StatusName @@ -94,37 +95,16 @@ def is_interaction_content_block_code(code: object) -> bool: 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]: +def api_error_fields(body: object) -> tuple[str | None, str | int | None]: """The message and code of an API error body, or ``(None, None)`` when it isn't one.""" try: - parsed = ApiErrorBody.model_validate(body) + parsed = API_ERROR_BODY_ADAPTER.validate_python(body) except ValidationError: return None, None - if parsed.error is None: + error = parsed.get('error') + if error is None: return None, None - message = parsed.error.message - return (str(message) if message is not None else None), parsed.error.code + return error.get('message'), error.get('code') def unwrap_error_body(body: object) -> object: diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_types.py b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_types.py new file mode 100644 index 000000000..81b0bd97f --- /dev/null +++ b/packages/genkit-google-genai/src/genkit_google_genai/_interactions/_types.py @@ -0,0 +1,1205 @@ +# 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 + +"""Wire types for the Gemini Interactions API (steps schema). + +Mirrors js/plugins/google-genai/src/common/interaction-types.ts: same type +names, same order. Keep the two in step: change JS first, then translate. + +How the JS types map to Python: + +- Each type is a TypedDict: the wire JSON itself. The plugin builds them as + dict literals and sends them as they are. ``extra_items=object`` keeps + fields not listed here, so new server fields pass through and are sent + back unchanged. +- Responses are validated against these TypedDicts with pydantic + (``parse_interaction``, ``parse_sse_event``). Nothing is filled in: a key + is there only when the server sent it. +- Only ``type`` (``event_type`` for events) is required. JS doesn't check + responses at runtime, so a field the server leaves out is ``undefined`` + there; here a required field would fail the whole response. The plugin's + own code still sets every field the JS types require. +- Steps, content, text annotations, stream deltas and SSE events are open + unions tagged by ``type`` (``event_type``): an unknown tag, or a known tag + whose fields don't match its type, validates as ``UnknownStep``, + ``UnknownContent``, ... These are ``dict`` subclasses holding the object + as sent (not TypedDicts, which type checkers can't tell apart from the + known types). Check ``isinstance(step, UnknownStep)`` first; after that, + comparing ``type`` narrows to one type (pyright, ty and pyrefly). +- JS open string unions (``'a' | 'b' | (string & {})``) are ``str``, with + the known values in a comment. +- JS inline object types get a name here (e.g. ``QueriesArguments`` and the + SSE event types). + +Python only: + +- ``ModelOutputStep.error``: the spec's step error, read by the converters. +- ``ApiErrorBody``: the body of a failed HTTP call (JS checks it inline). + +Not ported yet (translate from the JS file when the feature arrives): + +- ``Content`` as a ``Step`` (input given as plain content blocks): the + plugin sends and reads steps only. +- InteractionToolChoiceConfig, SpeechConfig, ImageConfig, VideoConfig, + ModelGenerationConfig, the agent configs, ServiceTier, + InteractionSafetySetting and CreateInteractionRequest: the create body is + still built as a plain dict; they come with the request mapping for + Gemini models. +- InteractionStreamResult: comes with the streaming client. +""" + +from __future__ import annotations + +from typing import Annotated, Literal, TypeAlias, TypeVar + +from pydantic import ( + Discriminator, + PlainValidator, + Tag, + TypeAdapter, + ValidationError, + ValidatorFunctionWrapHandler, + WrapValidator, +) +from typing_extensions import NotRequired, TypedDict + +# --------------------------------------------------------------------------- +# Open unions +# +# A union tagged by `type` (or `event_type`) that also takes tags it doesn't +# know: +# Annotated[ +# Annotated[Known, Tag(KNOWN_TAG)] +# | Annotated[UnknownX, keep_as(UnknownX, key), Tag(UNKNOWN_TAG)], +# open_union_tag(key, KNOWN_TYPES), +# keep_unknown(UnknownX, key), +# ] +# A known tag is validated against its type; an unknown tag, or a known tag +# whose fields don't match, is kept unchanged as an `UnknownX` instance. +# --------------------------------------------------------------------------- + +KNOWN_TAG = 'known' +UNKNOWN_TAG = 'unknown' + + +class UnknownObject(dict[str, object]): + """Base of the ``Unknown*`` types: a wire object kept exactly as sent.""" + + +_U = TypeVar('_U', bound=UnknownObject) + + +def tag_of(value: object, key: str) -> str | None: + """The string under ``key`` when ``value`` is a dict (wire JSON), else None.""" + if isinstance(value, dict): + # Read through items(): after isinstance on an `object`, type checkers + # don't know the key type, so `value.get(key)` doesn't type-check. + for name, item in value.items(): + if name == key: + return item if isinstance(item, str) else None + return None + + +def open_union_tag(key: str, known: frozenset[str]) -> Discriminator: + """Pick the known or the unknown branch of an open union by the value's tag.""" + + def tag(value: object) -> str: + return KNOWN_TAG if tag_of(value, key) in known else UNKNOWN_TAG + + return Discriminator(tag) + + +def as_unknown(cls: type[_U], key: str, value: object) -> _U: + """``value`` (an object with a string ``key``) as an ``Unknown*`` instance; raises ValueError otherwise.""" + if tag_of(value, key) is None or not isinstance(value, dict): + raise ValueError(f"expected an object with a string '{key}'") + return cls({str(name): item for name, item in value.items()}) + + +def keep_as(cls: type[UnknownObject], key: str) -> PlainValidator: + """Validator of the unknown branch: keep the object as sent, as a ``cls`` instance.""" + return PlainValidator(lambda value: as_unknown(cls, key, value)) + + +def keep_unknown(cls: type[UnknownObject], key: str) -> WrapValidator: + """Keep an object with a known tag whose fields don't match its type, as a ``cls`` instance.""" + + def validate(value: object, handler: ValidatorFunctionWrapHandler) -> object: + try: + return handler(value) + except ValidationError: + if tag_of(value, key) is not None: + return as_unknown(cls, key, value) + raise + + return WrapValidator(validate) + + +# --------------------------------------------------------------------------- +# Tools +# --------------------------------------------------------------------------- + + +class InteractionFunctionTool(TypedDict, extra_items=object): + """A function the model can call (https://ai.google.dev/gemini-api/docs/function-calling).""" + + type: Literal['function'] + # The name of the function to call. + name: NotRequired[str] + # Description and purpose of the function. + description: NotRequired[str] + # The function's parameters, as a JSON schema. + parameters: NotRequired[dict[str, object]] + + +class InteractionGoogleSearchTool(TypedDict, extra_items=object): + """Lets the model search Google (https://ai.google.dev/gemini-api/docs/grounding).""" + + type: Literal['google_search'] + # `web_search`, `image_search` or `enterprise_web_search`; unknown search + # types are passed through for forward compatibility. + search_types: NotRequired[list[str]] + + +class InteractionCodeExecutionTool(TypedDict, extra_items=object): + """Lets the model run code (https://ai.google.dev/gemini-api/docs/code-execution).""" + + type: Literal['code_execution'] + + +class InteractionUrlContextTool(TypedDict, extra_items=object): + """Lets the model read and summarize web page content.""" + + type: Literal['url_context'] + + +class InteractionFileSearchTool(TypedDict, extra_items=object): + """Lets the model search uploaded document corpora.""" + + type: Literal['file_search'] + file_search_store_names: NotRequired[list[str]] + metadata_filter: NotRequired[str] + top_k: NotRequired[int] + + +class InteractionAllowedTools(TypedDict, extra_items=object): + """The tools an MCP server tool may use.""" + + mode: NotRequired[str] + tools: NotRequired[list[str]] + + +class InteractionMcpServerTool(TypedDict, extra_items=object): + """Lets the model connect to remote MCP servers.""" + + type: Literal['mcp_server'] + name: NotRequired[str] + url: NotRequired[str] + headers: NotRequired[dict[str, str]] + allowed_tools: NotRequired[list[InteractionAllowedTools]] + + +class InteractionGoogleMapsTool(TypedDict, extra_items=object): + """Lets the model search Google Maps.""" + + type: Literal['google_maps'] + enable_widget: NotRequired[bool] + latitude: NotRequired[float] + longitude: NotRequired[float] + + +class InteractionComputerUseTool(TypedDict, extra_items=object): + """Lets the model use a computer.""" + + type: Literal['computer_use'] + disabled_safety_policies: NotRequired[list[str]] + enable_prompt_injection_detection: NotRequired[bool] + environment: NotRequired[str] + excluded_predefined_functions: NotRequired[list[str]] + + +class InteractionRetrievalTool(TypedDict, extra_items=object): + """Lets the model retrieve from external search or RAG stores.""" + + type: Literal['retrieval'] + exa_ai_search_config: NotRequired[dict[str, object]] + parallel_ai_search_config: NotRequired[dict[str, object]] + rag_store_config: NotRequired[dict[str, object]] + retrieval_types: NotRequired[list[str]] + vertex_ai_search_config: NotRequired[dict[str, object]] + + +class InteractionDynamicTool(TypedDict, extra_items=object): + """Any other tool, sent as given.""" + + type: str + + +InteractionTool: TypeAlias = ( + InteractionFunctionTool + | InteractionGoogleSearchTool + | InteractionCodeExecutionTool + | InteractionUrlContextTool + | InteractionFileSearchTool + | InteractionMcpServerTool + | InteractionGoogleMapsTool + | InteractionComputerUseTool + | InteractionRetrievalTool + | InteractionDynamicTool +) +"""A tool that can be used by the model.""" + +# --------------------------------------------------------------------------- +# Text annotations +# --------------------------------------------------------------------------- + + +class UrlCitation(TypedDict, extra_items=object): + """A URL citation annotation.""" + + type: Literal['url_citation'] + # Start of the annotated segment (in bytes). + start_index: NotRequired[int] + # End of the annotated segment, exclusive. + end_index: NotRequired[int] + url: NotRequired[str] + title: NotRequired[str] + + +class FileCitation(TypedDict, extra_items=object): + """A file citation annotation.""" + + type: Literal['file_citation'] + start_index: NotRequired[int] + end_index: NotRequired[int] + document_uri: NotRequired[str] + file_name: NotRequired[str] + # Source attributed for a portion of the text. + source: NotRequired[str] + page_number: NotRequired[int] + # Media ID in case of image citations. + media_id: NotRequired[str] + # User-provided metadata about the retrieved context. + custom_metadata: NotRequired[dict[str, object]] + + +class ReviewSnippet(TypedDict, extra_items=object): + """One review snippet of a place citation (inline in JS).""" + + review_id: NotRequired[str] + title: NotRequired[str] + url: NotRequired[str] + + +class PlaceCitation(TypedDict, extra_items=object): + """A place (Google Maps) citation annotation.""" + + type: Literal['place_citation'] + start_index: NotRequired[int] + end_index: NotRequired[int] + name: NotRequired[str] + # In `places/{place_id}` format. + place_id: NotRequired[str] + url: NotRequired[str] + review_snippets: NotRequired[list[ReviewSnippet]] + + +class SpeechAnnotation(TypedDict, extra_items=object): + """Assigns a TTS input turn to a speaker and sets its delivery style.""" + + type: Literal['speech_metadata'] + start_index: NotRequired[int] + end_index: NotRequired[int] + # The speaker to associate with this turn. + speaker: NotRequired[str] + # Style instruction for the speech synthesis. + style: NotRequired[str] + + +class WordInfo(TypedDict, extra_items=object): + """Word-level speech recognition annotation for transcription output.""" + + type: Literal['word_info'] + start_index: NotRequired[int] + end_index: NotRequired[int] + text: NotRequired[str] + # Offsets in time relative to the start of the audio. + start_offset: NotRequired[str] + end_offset: NotRequired[str] + # Speaker label for this word (e.g. "spk_1"). + speaker: NotRequired[str] + + +class UnknownTextAnnotation(UnknownObject): + """A text annotation type this plugin doesn't know yet (or doesn't match its type), kept as sent.""" + + +TEXT_ANNOTATION_TYPES = frozenset({'url_citation', 'file_citation', 'place_citation', 'speech_metadata', 'word_info'}) + +KnownTextAnnotation: TypeAlias = Annotated[ + UrlCitation | FileCitation | PlaceCitation | SpeechAnnotation | WordInfo, + Discriminator('type'), +] +TextAnnotation: TypeAlias = Annotated[ + Annotated[KnownTextAnnotation, Tag(KNOWN_TAG)] + | Annotated[UnknownTextAnnotation, keep_as(UnknownTextAnnotation, 'type'), Tag(UNKNOWN_TAG)], + open_union_tag('type', TEXT_ANNOTATION_TYPES), + keep_unknown(UnknownTextAnnotation, 'type'), +] +"""An annotation on text content, tagged by ``type``.""" + +# --------------------------------------------------------------------------- +# Content +# --------------------------------------------------------------------------- + + +class TextContent(TypedDict, extra_items=object): + """A text content block.""" + + type: Literal['text'] + text: NotRequired[str] + # Citations on model output, or speech metadata on TTS input. + annotations: NotRequired[list[TextAnnotation]] + + +class ImageContent(TypedDict, extra_items=object): + """An image content block.""" + + type: Literal['image'] + # Base64 image bytes. + data: NotRequired[str] + uri: NotRequired[str] + mime_type: NotRequired[str] + # MediaResolution: `low`, `medium`, `high` or `ultra_high`. + resolution: NotRequired[str] + + +class AudioContent(TypedDict, extra_items=object): + """An audio content block.""" + + type: Literal['audio'] + data: NotRequired[str] + uri: NotRequired[str] + mime_type: NotRequired[str] + # Sent on streamed audio (copied onto the content when the stream is + # assembled), e.g. single-voice TTS, which has no `mime_type`. + sample_rate: NotRequired[int] + channels: NotRequired[int] + + +class DocumentContent(TypedDict, extra_items=object): + """A document content block.""" + + type: Literal['document'] + data: NotRequired[str] + uri: NotRequired[str] + mime_type: NotRequired[str] + + +class VideoContent(TypedDict, extra_items=object): + """A video content block.""" + + type: Literal['video'] + data: NotRequired[str] + uri: NotRequired[str] + mime_type: NotRequired[str] + # MediaResolution: `low`, `medium`, `high` or `ultra_high`. + resolution: NotRequired[str] + # VideoProcessing: `static` (frames at 1 FPS, the default) or `agentic` + # (the model explores the timeline and loads only what it needs). + processing: NotRequired[str] + + +class ThoughtContent(TypedDict, extra_items=object): + """A thought content block.""" + + type: Literal['thought'] + # Signature to match the backend source to be part of the generation. + signature: NotRequired[str] + # JS: text and image only. Any content is accepted here, so another type + # doesn't turn the whole step into an unknown one. + summary: NotRequired[list[Content]] + + +class FunctionCallContent(TypedDict, extra_items=object): + """A function tool call content block.""" + + type: Literal['function_call'] + name: NotRequired[str] + arguments: NotRequired[dict[str, object]] + # A unique ID for this specific tool call. + id: NotRequired[str] + + +class FunctionResultContent(TypedDict, extra_items=object): + """A function tool result content block.""" + + type: Literal['function_result'] + name: NotRequired[str] + is_error: NotRequired[bool] + result: NotRequired[dict[str, object] | str] + # The ID of the function call this answers. + call_id: NotRequired[str] + + +CONTENT_TYPES = frozenset({ + 'text', + 'image', + 'audio', + 'document', + 'video', + 'thought', + 'function_call', + 'function_result', +}) + + +class UnknownContent(UnknownObject): + """A content type this plugin doesn't know yet (or doesn't match its type), kept as sent.""" + + +KnownContent: TypeAlias = Annotated[ + TextContent + | ImageContent + | AudioContent + | DocumentContent + | VideoContent + | ThoughtContent + | FunctionCallContent + | FunctionResultContent, + Discriminator('type'), +] +Content: TypeAlias = Annotated[ + Annotated[KnownContent, Tag(KNOWN_TAG)] + | Annotated[UnknownContent, keep_as(UnknownContent, 'type'), Tag(UNKNOWN_TAG)], + open_union_tag('type', CONTENT_TYPES), + keep_unknown(UnknownContent, 'type'), +] +"""The content of a step, tagged by ``type``.""" + +# --------------------------------------------------------------------------- +# Steps +# +# Tool call/result steps: only `type` is required here (see the module +# docstring). The platform omits fields the spec marks as required at times +# (e.g. a `google_search_call` without `arguments`), so content fields are +# sent back only when present. +# --------------------------------------------------------------------------- + + +class Status(TypedDict, extra_items=object): + """A step error (google.rpc.Status). Python only: read by the converters.""" + + # A google.rpc code. + code: NotRequired[int] + message: NotRequired[str] + + +class ModelOutputStep(TypedDict, extra_items=object): + """Output from the model. + + ``content`` is optional: the server can end a response with an empty + ``{type: 'model_output'}`` step (seen live on vertexAI with Google Maps). + """ + + type: Literal['model_output'] + content: NotRequired[list[Content]] + error: NotRequired[Status] + + +class UserInputStep(TypedDict, extra_items=object): + """Input from the user.""" + + type: Literal['user_input'] + content: NotRequired[list[Content]] + + +class QueriesArguments(TypedDict, extra_items=object): + """The arguments of a Google Search or Google Maps call (inline in JS).""" + + queries: NotRequired[list[str]] + + +class UrlsArguments(TypedDict, extra_items=object): + """The arguments of a URL context call (inline in JS).""" + + urls: NotRequired[list[str]] + + +class CodeArguments(TypedDict, extra_items=object): + """The arguments of a code execution call (inline in JS).""" + + code: NotRequired[str] + # `python` or `bash`. + language: NotRequired[str] + + +class GoogleSearchCallStep(TypedDict, extra_items=object): + """A Google Search call the server ran.""" + + type: Literal['google_search_call'] + id: NotRequired[str] + arguments: NotRequired[QueriesArguments] + # `web_search`, `image_search` or `enterprise_web_search`. + search_type: NotRequired[str] + signature: NotRequired[str] + + +class GoogleSearchResultStep(TypedDict, extra_items=object): + """The result of a Google Search call.""" + + type: Literal['google_search_result'] + call_id: NotRequired[str] + # The search results, e.g. `[{search_suggestions}]`. + result: NotRequired[list[dict[str, object]] | dict[str, object]] + is_error: NotRequired[bool] + signature: NotRequired[str] + + +class CodeExecutionCallStep(TypedDict, extra_items=object): + """A code execution call the server ran.""" + + type: Literal['code_execution_call'] + id: NotRequired[str] + arguments: NotRequired[CodeArguments] + signature: NotRequired[str] + + +class CodeExecutionResultStep(TypedDict, extra_items=object): + """The result of a code execution call.""" + + type: Literal['code_execution_result'] + call_id: NotRequired[str] + result: NotRequired[dict[str, object] | str] + signature: NotRequired[str] + + +class FunctionCallStep(TypedDict, extra_items=object): + """A function call: for the client to run, or already run by the server (e.g. Antigravity).""" + + type: Literal['function_call'] + name: NotRequired[str] + arguments: NotRequired[dict[str, object]] + id: NotRequired[str] + signature: NotRequired[str] + + +class FunctionResultStep(TypedDict, extra_items=object): + """The result of a function call.""" + + type: Literal['function_result'] + name: NotRequired[str] + call_id: NotRequired[str] + is_error: NotRequired[bool] + # JS: text and image content only in the list. Any content is accepted. + result: NotRequired[dict[str, object] | str | list[Content]] + signature: NotRequired[str] + + +class ThoughtStep(TypedDict, extra_items=object): + """A thought, with its signature.""" + + type: Literal['thought'] + signature: NotRequired[str] + # JS: text and image only. Any content is accepted. + summary: NotRequired[list[Content]] + + +class ProcessingCallStep(TypedDict, extra_items=object): + """Agentic video understanding: the model asked to load part of a video. Needs no reply.""" + + type: Literal['processing_call'] + id: NotRequired[str] + signature: NotRequired[str] + + +class ProcessingResultStep(TypedDict, extra_items=object): + """Agentic video understanding: the result of a ``processing_call``.""" + + type: Literal['processing_result'] + call_id: NotRequired[str] + signature: NotRequired[str] + + +# Server-side built-in tool steps. The server runs these tools itself; the +# steps (with their signatures) must be sent back in the history so the model +# keeps the tool results in later turns. + + +class UrlContextCallStep(TypedDict, extra_items=object): + """A URL context call the server ran.""" + + type: Literal['url_context_call'] + id: NotRequired[str] + arguments: NotRequired[UrlsArguments] + signature: NotRequired[str] + + +class UrlContextResultStep(TypedDict, extra_items=object): + """The result of a URL context call.""" + + type: Literal['url_context_result'] + call_id: NotRequired[str] + # One entry per URL: `{url, status}` (`success`, `error`, ...). + result: NotRequired[list[dict[str, object]]] + is_error: NotRequired[bool] + signature: NotRequired[str] + + +class FileSearchCallStep(TypedDict, extra_items=object): + """A file search call the server ran.""" + + type: Literal['file_search_call'] + id: NotRequired[str] + signature: NotRequired[str] + + +class FileSearchResultStep(TypedDict, extra_items=object): + """The result of a file search call.""" + + type: Literal['file_search_result'] + call_id: NotRequired[str] + # Not in the spec's step schema, but the streamed delta carries it (and + # the stream assembly copies it into the step), so it's kept. + result: NotRequired[list[dict[str, object]]] + signature: NotRequired[str] + + +class GoogleMapsCallStep(TypedDict, extra_items=object): + """A Google Maps call the server ran.""" + + type: Literal['google_maps_call'] + id: NotRequired[str] + arguments: NotRequired[QueriesArguments] + signature: NotRequired[str] + + +class GoogleMapsResultStep(TypedDict, extra_items=object): + """The result of a Google Maps call.""" + + type: Literal['google_maps_result'] + call_id: NotRequired[str] + # e.g. `[{places: [{place_id, name, url}]}]`. + result: NotRequired[list[dict[str, object]]] + signature: NotRequired[str] + + +class McpServerToolCallStep(TypedDict, extra_items=object): + """An MCP server tool call the server ran (no signature in the spec).""" + + type: Literal['mcp_server_tool_call'] + id: NotRequired[str] + name: NotRequired[str] + server_name: NotRequired[str] + arguments: NotRequired[dict[str, object]] + + +class McpServerToolResultStep(TypedDict, extra_items=object): + """The result of an MCP server tool call.""" + + type: Literal['mcp_server_tool_result'] + call_id: NotRequired[str] + name: NotRequired[str] + server_name: NotRequired[str] + # JS: text and image content only in the list. Any content is accepted. + result: NotRequired[dict[str, object] | str | list[Content]] + + +BuiltInToolStep: TypeAlias = ( + UrlContextCallStep + | UrlContextResultStep + | FileSearchCallStep + | FileSearchResultStep + | GoogleMapsCallStep + | GoogleMapsResultStep + | McpServerToolCallStep + | McpServerToolResultStep +) + + +class UnknownStep(UnknownObject): + """A step type this plugin doesn't know yet (or doesn't match its type), kept as sent.""" + + +STEP_TYPES = frozenset({ + 'model_output', + 'user_input', + 'google_search_call', + 'google_search_result', + 'code_execution_call', + 'code_execution_result', + 'function_call', + 'function_result', + 'thought', + 'processing_call', + 'processing_result', + 'url_context_call', + 'url_context_result', + 'file_search_call', + 'file_search_result', + 'google_maps_call', + 'google_maps_result', + 'mcp_server_tool_call', + 'mcp_server_tool_result', +}) + +KnownStep: TypeAlias = Annotated[ + ModelOutputStep + | UserInputStep + | GoogleSearchCallStep + | GoogleSearchResultStep + | CodeExecutionCallStep + | CodeExecutionResultStep + | FunctionCallStep + | FunctionResultStep + | ThoughtStep + | ProcessingCallStep + | ProcessingResultStep + | BuiltInToolStep, + Discriminator('type'), +] +Step: TypeAlias = Annotated[ + Annotated[KnownStep, Tag(KNOWN_TAG)] | Annotated[UnknownStep, keep_as(UnknownStep, 'type'), Tag(UNKNOWN_TAG)], + open_union_tag('type', STEP_TYPES), + keep_unknown(UnknownStep, 'type'), +] +"""A step of the interaction timeline, tagged by ``type``.""" + +# --------------------------------------------------------------------------- +# Usage +# --------------------------------------------------------------------------- + + +class ModalityTokens(TypedDict, extra_items=object): + """The token count for a single modality.""" + + # ResponseModality: `text`, `image`, `audio`, ... + modality: NotRequired[str] + tokens: NotRequired[int] + + +class GroundingToolCount(TypedDict, extra_items=object): + """The number of times a grounding tool was used.""" + + # The grounding tool, e.g. `google_search` or `google_maps`. + type: NotRequired[str] + count: NotRequired[int] + + +class Usage(TypedDict, extra_items=object): + """Statistics on the interaction request's token usage.""" + + # Tokens in the prompt (context). + total_input_tokens: NotRequired[int] + input_tokens_by_modality: NotRequired[list[ModalityTokens]] + # Tokens in the cached part of the prompt. + total_cached_tokens: NotRequired[int] + cached_tokens_by_modality: NotRequired[list[ModalityTokens]] + # Tokens across all the generated responses. + total_output_tokens: NotRequired[int] + output_tokens_by_modality: NotRequired[list[ModalityTokens]] + # Tokens in tool-use prompts. + total_tool_use_tokens: NotRequired[int] + tool_use_tokens_by_modality: NotRequired[list[ModalityTokens]] + # Thought tokens of thinking models. + total_thought_tokens: NotRequired[int] + # Prompt + responses + other internal tokens. + total_tokens: NotRequired[int] + grounding_tool_count: NotRequired[list[GroundingToolCount]] + + +# --------------------------------------------------------------------------- +# Stream deltas (the `delta` of a `step.delta` event). Not used until the +# streaming client arrives; kept in step with JS. +# --------------------------------------------------------------------------- + + +class TextDelta(TypedDict, extra_items=object): + type: Literal['text'] + text: NotRequired[str] + + +class ImageDelta(TypedDict, extra_items=object): + type: Literal['image'] + data: NotRequired[str] + uri: NotRequired[str] + mime_type: NotRequired[str] + resolution: NotRequired[str] + + +class AudioDelta(TypedDict, extra_items=object): + type: Literal['audio'] + data: NotRequired[str] + uri: NotRequired[str] + mime_type: NotRequired[str] + sample_rate: NotRequired[int] + channels: NotRequired[int] + + +class DocumentDelta(TypedDict, extra_items=object): + type: Literal['document'] + data: NotRequired[str] + uri: NotRequired[str] + mime_type: NotRequired[str] + + +class VideoDelta(TypedDict, extra_items=object): + type: Literal['video'] + data: NotRequired[str] + uri: NotRequired[str] + mime_type: NotRequired[str] + resolution: NotRequired[str] + + +class ThoughtSummaryDelta(TypedDict, extra_items=object): + type: Literal['thought_summary'] + content: NotRequired[Content] + + +class ThoughtSignatureDelta(TypedDict, extra_items=object): + type: Literal['thought_signature'] + signature: NotRequired[str] + + +class ArgumentsDelta(TypedDict, extra_items=object): + type: Literal['arguments_delta'] + # A piece of the function call's JSON arguments. + arguments: NotRequired[str] + + +class CodeExecutionCallDelta(TypedDict, extra_items=object): + type: Literal['code_execution_call'] + arguments: NotRequired[CodeArguments] + signature: NotRequired[str] + + +class UrlContextCallDelta(TypedDict, extra_items=object): + type: Literal['url_context_call'] + arguments: NotRequired[UrlsArguments] + signature: NotRequired[str] + + +class GoogleSearchCallDelta(TypedDict, extra_items=object): + type: Literal['google_search_call'] + arguments: NotRequired[QueriesArguments] + signature: NotRequired[str] + + +class McpServerToolCallDelta(TypedDict, extra_items=object): + type: Literal['mcp_server_tool_call'] + name: NotRequired[str] + server_name: NotRequired[str] + arguments: NotRequired[dict[str, object]] + + +class FileSearchCallDelta(TypedDict, extra_items=object): + type: Literal['file_search_call'] + signature: NotRequired[str] + + +class GoogleMapsCallDelta(TypedDict, extra_items=object): + type: Literal['google_maps_call'] + arguments: NotRequired[QueriesArguments] + signature: NotRequired[str] + + +class FunctionResultDelta(TypedDict, extra_items=object): + type: Literal['function_result'] + name: NotRequired[str] + call_id: NotRequired[str] + is_error: NotRequired[bool] + result: NotRequired[dict[str, object] | str | list[Content]] + + +class CodeExecutionResultDelta(TypedDict, extra_items=object): + type: Literal['code_execution_result'] + result: NotRequired[str] + is_error: NotRequired[bool] + signature: NotRequired[str] + + +class UrlContextResultDelta(TypedDict, extra_items=object): + type: Literal['url_context_result'] + result: NotRequired[list[dict[str, object]]] + is_error: NotRequired[bool] + signature: NotRequired[str] + + +class GoogleSearchResultDelta(TypedDict, extra_items=object): + type: Literal['google_search_result'] + result: NotRequired[list[dict[str, object]]] + is_error: NotRequired[bool] + signature: NotRequired[str] + + +class McpServerToolResultDelta(TypedDict, extra_items=object): + type: Literal['mcp_server_tool_result'] + name: NotRequired[str] + server_name: NotRequired[str] + result: NotRequired[dict[str, object] | str | list[Content]] + + +class FileSearchResultDelta(TypedDict, extra_items=object): + type: Literal['file_search_result'] + result: NotRequired[list[dict[str, object]]] + signature: NotRequired[str] + + +class GoogleMapsResultDelta(TypedDict, extra_items=object): + type: Literal['google_maps_result'] + result: NotRequired[list[dict[str, object]]] + signature: NotRequired[str] + + +class ProcessingCallDelta(TypedDict, extra_items=object): + type: Literal['processing_call'] + signature: NotRequired[str] + + +class ProcessingResultDelta(TypedDict, extra_items=object): + type: Literal['processing_result'] + signature: NotRequired[str] + + +class TextAnnotationDelta(TypedDict, extra_items=object): + type: Literal['text_annotation_delta'] + annotations: NotRequired[list[TextAnnotation]] + + +class UnknownStepDelta(UnknownObject): + """A delta type this plugin doesn't know yet (or doesn't match its type), kept as sent.""" + + +STEP_DELTA_TYPES = frozenset({ + 'text', + 'image', + 'audio', + 'document', + 'video', + 'thought_summary', + 'thought_signature', + 'arguments_delta', + 'code_execution_call', + 'url_context_call', + 'google_search_call', + 'mcp_server_tool_call', + 'file_search_call', + 'google_maps_call', + 'function_result', + 'code_execution_result', + 'url_context_result', + 'google_search_result', + 'mcp_server_tool_result', + 'file_search_result', + 'google_maps_result', + 'processing_call', + 'processing_result', + 'text_annotation_delta', +}) + +KnownStepDelta: TypeAlias = Annotated[ + TextDelta + | ImageDelta + | AudioDelta + | DocumentDelta + | VideoDelta + | ThoughtSummaryDelta + | ThoughtSignatureDelta + | ArgumentsDelta + | CodeExecutionCallDelta + | UrlContextCallDelta + | GoogleSearchCallDelta + | McpServerToolCallDelta + | FileSearchCallDelta + | GoogleMapsCallDelta + | FunctionResultDelta + | CodeExecutionResultDelta + | UrlContextResultDelta + | GoogleSearchResultDelta + | McpServerToolResultDelta + | FileSearchResultDelta + | GoogleMapsResultDelta + | ProcessingCallDelta + | ProcessingResultDelta + | TextAnnotationDelta, + Discriminator('type'), +] +StepDeltaData: TypeAlias = Annotated[ + Annotated[KnownStepDelta, Tag(KNOWN_TAG)] + | Annotated[UnknownStepDelta, keep_as(UnknownStepDelta, 'type'), Tag(UNKNOWN_TAG)], + open_union_tag('type', STEP_DELTA_TYPES), + keep_unknown(UnknownStepDelta, 'type'), +] +"""The ``delta`` of a ``step.delta`` event, tagged by ``type``.""" + +# --------------------------------------------------------------------------- +# The interaction and its errors +# --------------------------------------------------------------------------- + + +class InteractionError(TypedDict, extra_items=object): + """An error recorded on an interaction or sent in an SSE ``error`` event.""" + + # Error code, e.g. `safety` or `malformed_function_call`. JS types it as + # a string; an HTTP error body can carry a number. + code: NotRequired[str | int] + # Human-readable error message. + message: NotRequired[str] + + +class ApiErrorBody(TypedDict, extra_items=object): + """The body of a failed API call: ``{"error": {"code": ..., "message": ...}}``. Python only.""" + + error: NotRequired[InteractionError] + + +class GeminiInteraction(TypedDict, extra_items=object): + """An interaction, as the API returns it.""" + + # The model or agent used for the interaction. + model: NotRequired[str] + agent: NotRequired[str] + # The environment ID for the sandbox, if used. + environment_id: NotRequired[str] + # The ID to continue from in later interactions (`v1_...`). + id: NotRequired[str] + previous_interaction_id: NotRequired[str] + # `in_progress`, `queued`, `requires_action`, `completed`, `incomplete`, + # `failed` or `cancelled` (JS lists these; Python also handles + # `budget_exceeded`). + status: NotRequired[str] + # ISO 8601 times. + created: NotRequired[str] + updated: NotRequired[str] + role: NotRequired[str] + # Steps comprising the interaction timeline. + steps: NotRequired[list[Step]] + usage: NotRequired[Usage] + # Set when `status` is `failed` (e.g. a safety block or an unrecoverable + # tool-call error). + errors: NotRequired[list[InteractionError]] + + +# --------------------------------------------------------------------------- +# SSE events (inline object types in JS's InteractionSseEvent) +# --------------------------------------------------------------------------- + + +class InteractionCreatedEvent(TypedDict, extra_items=object): + event_type: Literal['interaction.created'] + interaction: NotRequired[GeminiInteraction] + event_id: NotRequired[str] + + +class InteractionCompletedEvent(TypedDict, extra_items=object): + event_type: Literal['interaction.completed'] + interaction: NotRequired[GeminiInteraction] + event_id: NotRequired[str] + + +class InteractionStatusUpdateEvent(TypedDict, extra_items=object): + event_type: Literal['interaction.status_update'] + # Only present when the interaction is stored (`store: true`). + interaction_id: NotRequired[str] + status: NotRequired[str] + event_id: NotRequired[str] + + +class InteractionErrorEvent(TypedDict, extra_items=object): + event_type: Literal['error'] + error: NotRequired[InteractionError] + event_id: NotRequired[str] + + +class StepStartEvent(TypedDict, extra_items=object): + event_type: Literal['step.start'] + index: NotRequired[int] + step: NotRequired[Step] + event_id: NotRequired[str] + + +class StepDeltaEvent(TypedDict, extra_items=object): + event_type: Literal['step.delta'] + index: NotRequired[int] + delta: NotRequired[StepDeltaData] + event_id: NotRequired[str] + + +class StepStopEvent(TypedDict, extra_items=object): + event_type: Literal['step.stop'] + index: NotRequired[int] + # Usage so far in the interaction (sent by vertexAI). + usage: NotRequired[Usage] + # Usage of this step. + step_usage: NotRequired[Usage] + event_id: NotRequired[str] + + +class UnknownSseEvent(UnknownObject): + """An event type this plugin doesn't know yet (or doesn't match its type), kept as sent.""" + + +SSE_EVENT_TYPES = frozenset({ + 'interaction.created', + 'interaction.completed', + 'interaction.status_update', + 'error', + 'step.start', + 'step.delta', + 'step.stop', +}) + +KnownSseEvent: TypeAlias = Annotated[ + InteractionCreatedEvent + | InteractionCompletedEvent + | InteractionStatusUpdateEvent + | InteractionErrorEvent + | StepStartEvent + | StepDeltaEvent + | StepStopEvent, + Discriminator('event_type'), +] +InteractionSseEvent: TypeAlias = Annotated[ + Annotated[KnownSseEvent, Tag(KNOWN_TAG)] + | Annotated[UnknownSseEvent, keep_as(UnknownSseEvent, 'event_type'), Tag(UNKNOWN_TAG)], + open_union_tag('event_type', SSE_EVENT_TYPES), + keep_unknown(UnknownSseEvent, 'event_type'), +] +"""One server-sent event of a streamed interaction, tagged by ``event_type``.""" + +# --------------------------------------------------------------------------- +# Parsing and checks +# --------------------------------------------------------------------------- + +INTERACTION_ADAPTER: TypeAdapter[GeminiInteraction] = TypeAdapter(GeminiInteraction) +STEP_ADAPTER: TypeAdapter[Step] = TypeAdapter(Step) +CONTENT_ADAPTER: TypeAdapter[Content] = TypeAdapter(Content) +SSE_EVENT_ADAPTER: TypeAdapter[InteractionSseEvent] = TypeAdapter(InteractionSseEvent) +API_ERROR_BODY_ADAPTER: TypeAdapter[ApiErrorBody] = TypeAdapter(ApiErrorBody) + + +def parse_interaction(body: object) -> GeminiInteraction: + """Validate a response body as an interaction (raises ``ValidationError`` when it isn't one). + + Unknown steps and content, and known ones whose fields don't match their + type, are kept as sent (``UnknownStep`` / ``UnknownContent``). + """ + return INTERACTION_ADAPTER.validate_python(body) + + +def parse_sse_event(data: object) -> InteractionSseEvent: + """Validate the JSON of one SSE ``data:`` line as an event.""" + return SSE_EVENT_ADAPTER.validate_python(data) diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_utils.py b/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_utils.py index 8c79d8396..7b8c9f4b5 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_utils.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_utils.py @@ -28,6 +28,7 @@ to_interaction_steps, ) from genkit_google_genai._interactions._options import ClientOptions +from genkit_google_genai._interactions._types import Step, UserInputStep from genkit_google_genai._models._routing import strip_ref_prefixes from genkit_google_genai._models._sdk_config import check_timeout_seconds, timeout_seconds_to_ms from genkit_google_genai._models._secrets import context_api_key @@ -219,7 +220,7 @@ def partition_keys( return (*parts, remainder) -def require_interaction_steps(steps: list[Any]) -> list[Any]: +def require_interaction_steps(steps: list[Step]) -> list[Step]: """Reject an empty Interactions input before we pay for a round trip.""" if not steps: raise GenkitError( @@ -229,18 +230,16 @@ def require_interaction_steps(steps: list[Any]) -> list[Any]: return steps -def steps_with_folded_system_instruction(messages: list[Message] | None) -> list[dict[str, Any]]: +def steps_with_folded_system_instruction(messages: list[Message] | None) -> list[Step]: """Convert messages to interaction steps, folding system prompt into a leading user turn.""" system_instruction, turns = split_system_instruction(messages or []) steps = to_interaction_steps(ensure_tool_ids(turns)) if system_instruction: - steps.insert( - 0, - { - 'type': 'user_input', - 'content': [{'type': 'text', 'text': system_instruction}], - }, - ) + instruction: UserInputStep = { + 'type': 'user_input', + 'content': [{'type': 'text', 'text': system_instruction}], + } + steps.insert(0, instruction) return require_interaction_steps(steps) 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 79fcfaa81..d3341c01d 100644 --- a/packages/genkit-google-genai/tests/interactions/interactions_client_test.py +++ b/packages/genkit-google-genai/tests/interactions/interactions_client_test.py @@ -36,7 +36,6 @@ timeout_seconds, ) from genkit_google_genai._interactions._options import ClientOptions -from google.genai.interactions import Interaction from genkit import GenkitError from genkit.plugin_api import GENKIT_USER_AGENT @@ -128,8 +127,7 @@ async def test_create_interaction_posts_body(http_client: MagicMock) -> None: ClientOptions(base_url='https://example.test'), ) - assert isinstance(result, Interaction) - assert result.id == 'ix-1' + assert result == {'id': 'ix-1', 'status': 'in_progress'} method, url = http_client.request.call_args.args[:2] assert method == 'POST' assert url == 'https://example.test/v1beta/interactions' @@ -148,7 +146,7 @@ async def test_get_interaction_gets_by_id(http_client: MagicMock) -> None: with patch.object(interactions_client, '_http_client', return_value=http_client): result = await get_interaction('key', 'ix-9') - assert result.id == 'ix-9' + assert result.get('id') == 'ix-9' method, url = http_client.request.call_args.args[:2] assert method == 'GET' assert url.endswith('/interactions/ix-9') @@ -163,8 +161,7 @@ async def test_cancel_interaction_normalizes_http_cancelled(http_client: MagicMo with patch.object(interactions_client, '_http_client', return_value=http_client): result = await cancel_interaction('key', 'ix-cancel') - assert result.id == 'ix-cancel' - assert result.status == 'cancelled' + assert result == {'id': 'ix-cancel', 'status': 'cancelled'} @pytest.mark.asyncio @@ -175,7 +172,7 @@ async def test_cancel_interaction_normalizes_success_as_cancelled(http_client: M with patch.object(interactions_client, '_http_client', return_value=http_client): result = await cancel_interaction('key', 'ix-cancel') - assert result.status == 'cancelled' + assert result == {'id': 'ix-cancel', 'status': 'cancelled'} @pytest.mark.asyncio @@ -184,8 +181,7 @@ async def test_cancel_interaction_empty_success_body_is_cancelled(http_client: M with patch.object(interactions_client, '_http_client', return_value=http_client): result = await cancel_interaction('key', 'ix-cancel') - assert result.id == 'ix-cancel' - assert result.status == 'cancelled' + assert result == {'id': 'ix-cancel', 'status': 'cancelled'} http_client.request.return_value = mock_response( status_code=404, json_body={'error': {'message': 'missing'}}, @@ -285,7 +281,7 @@ async def test_traces_create_interaction_with_experimental_debug_traces(http_cli ): result = await create_interaction('secret-key12', request_body, ClientOptions(experimental_debug_traces=True)) - assert result.id == 'ix-1' + assert result.get('id') == 'ix-1' assert len(recorder.calls) == 1 span = recorder.calls[0] assert span['name'] == 'httpRequest' @@ -341,7 +337,7 @@ async def test_cancel_is_not_traced(http_client: MagicMock) -> None: 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 result.get('status') == 'cancelled' assert recorder.calls == [] 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 581020b8b..ec3fc357a 100644 --- a/packages/genkit-google-genai/tests/interactions/interactions_converters_test.py +++ b/packages/genkit-google-genai/tests/interactions/interactions_converters_test.py @@ -18,7 +18,7 @@ from __future__ import annotations -from typing import Any, cast +from typing import Any import pytest from genkit_google_genai._interactions._converters import ( @@ -38,7 +38,7 @@ usage_from_interaction, with_basic_usage_stats, ) -from google.genai.interactions import Content, Interaction, Step, ThoughtStep, Usage +from genkit_google_genai._interactions._types import Content, Step, ThoughtStep, Usage, parse_interaction from pydantic import BaseModel, TypeAdapter from genkit import GenkitError, Media, Message, Part @@ -46,6 +46,8 @@ ContentAdapter: TypeAdapter[Content] = TypeAdapter(Content) StepAdapter: TypeAdapter[Step] = TypeAdapter(Step) +ThoughtStepAdapter: TypeAdapter[ThoughtStep] = TypeAdapter(ThoughtStep) +UsageAdapter: TypeAdapter[Usage] = TypeAdapter(Usage) def part_dict(part: Part) -> dict: @@ -521,11 +523,7 @@ def test_unknown_step_round_trips(self) -> None: assert to_interaction_steps(messages) == [blob] def test_unknown_step_inbound_then_outbound(self) -> None: - class FutureStep(BaseModel): - type: str = 'future_step' - payload: dict - - parts = from_interaction_step(cast(Any, FutureStep(payload={'x': 1}))) + parts = from_interaction_step(StepAdapter.validate_python({'type': 'future_step', 'payload': {'x': 1}})) root = parts[0] assert root.custom is not None assert (root.custom or {})['unknownStep']['type'] == 'future_step' @@ -552,7 +550,7 @@ def test_signed_multimodal_thought_replays_original_step(self) -> None: def test_thought_with_image_replays_the_original_step(self) -> None: """A thought whose summary has an image comes back as that same step.""" - step = ThoughtStep.model_validate({ + step = ThoughtStepAdapter.validate_python({ 'type': 'thought', 'signature': 'sig-img', 'summary': [ @@ -561,7 +559,7 @@ def test_thought_with_image_replays_the_original_step(self) -> None: ], }) part = from_thought_step(step) - assert to_thought_step(part) == step.model_dump(mode='python') + assert to_thought_step(part) == step def test_json_array_function_result_is_boxed(self) -> None: messages = [ @@ -681,7 +679,7 @@ def test_text(self) -> None: ContentAdapter.validate_python({ 'type': 'text', 'text': 'Hello world', - 'annotations': [{'start_index': 0, 'end_index': 5, 'source': 'source'}], + 'annotations': [{'type': 'file_citation', 'start_index': 0, 'end_index': 5, 'source': 'source'}], }) ) assert part_dict(result) == { @@ -750,7 +748,7 @@ def test_audio_uri_without_a_mime_type_is_not_labelled(self) -> None: assert part_dict(result) == {'media': {'url': 'gs://bucket/clip.mp3'}} def test_thought(self) -> None: - step = ThoughtStep.model_validate({ + step = ThoughtStepAdapter.validate_python({ 'type': 'thought', 'signature': 'SIG', 'summary': [{'type': 'text', 'text': 'Thinking...'}], @@ -762,6 +760,16 @@ def test_thought(self) -> None: assert dumped['custom']['thought']['type'] == 'thought' assert dumped['custom']['thought']['summary'] == [{'type': 'text', 'text': 'Thinking...'}] + def test_thought_without_a_signature_has_no_signature_metadata(self) -> None: + # Seen live on Antigravity: summary steps without a signature, and the + # signature in a separate step of its own. + summary_only = from_thought_step( + ThoughtStepAdapter.validate_python({'type': 'thought', 'summary': [{'type': 'text', 'text': 'Plan'}]}) + ) + assert summary_only.metadata is None + signature_only = from_thought_step(ThoughtStepAdapter.validate_python({'type': 'thought', 'signature': 'SIG'})) + assert signature_only.metadata == {'thoughtSignature': 'SIG'} + class TestFromInteractionStep: def test_model_output_includes_empty_annotations(self) -> None: @@ -839,6 +847,22 @@ def test_function_result_is_custom_stash_not_tool_response(self) -> None: assert stash['call_id'] == 'c1' assert stash['is_error'] is False + def test_function_result_resends_is_error_as_received(self) -> None: + # Antigravity sandbox results come with `is_error: false` (seen live); + # it's sent back as false, and left out when the server didn't send it. + with_false = parts_of({ + 'type': 'function_result', + 'call_id': 'c1', + 'name': 'list_dir', + 'result': 'app/', + 'is_error': False, + }) + without = parts_of({'type': 'function_result', 'call_id': 'c2', 'name': 'list_dir', 'result': ''}) + assert to_interaction_steps([Message(role='model', content=[*with_false, *without])]) == [ + {'type': 'function_result', 'name': 'list_dir', 'call_id': 'c1', 'result': 'app/', 'is_error': False}, + {'type': 'function_result', 'name': 'list_dir', 'call_id': 'c2', 'result': ''}, + ] + def test_failed_function_result_keeps_is_error_on_stash(self) -> None: result = from_interaction_step( StepAdapter.validate_python({ @@ -896,7 +920,7 @@ class TestInboundFlattensToSingleModelMessage: """Every Interaction response becomes one role=model Message of flattened parts.""" def test_mixed_tape_drops_user_input_and_keeps_order(self) -> None: - interaction = Interaction.model_validate({ + interaction = parse_interaction({ 'id': 'ix-1', 'status': 'completed', 'environment_id': 'env-1', @@ -1039,14 +1063,14 @@ def test_thought_round_trip_keeps_signature(self) -> None: def test_operation_does_not_persist_client_options() -> None: - op = from_interaction(Interaction.model_validate({'id': '123', 'status': 'in_progress'})) + op = from_interaction(parse_interaction({'id': '123', 'status': 'in_progress'})) assert not op.metadata class TestFromInteractionStatusMapping: def test_cancelled(self) -> None: - result = from_interaction(Interaction.model_validate({'id': '123', 'status': 'cancelled'})) + result = from_interaction(parse_interaction({'id': '123', 'status': 'cancelled'})) assert result.done is True assert result.output is not None assert result.output.finish_reason == 'aborted' @@ -1055,7 +1079,7 @@ def test_cancelled(self) -> None: def test_failed_exits_poll_loop(self) -> None: result = from_interaction( - Interaction.model_validate({ + parse_interaction({ 'id': '123', 'status': 'failed', 'steps': [{'type': 'model_output', 'error': {'code': 3, 'message': 'boom'}}], @@ -1066,14 +1090,14 @@ def test_failed_exits_poll_loop(self) -> None: assert result.error.message == 'boom' def test_failed_without_step_error_falls_back(self) -> None: - result = from_interaction(Interaction.model_validate({'id': '123', 'status': 'failed'})) + result = from_interaction(parse_interaction({'id': '123', 'status': 'failed'})) assert result.done is True assert result.error is not None assert result.error.message == 'Interaction failed' def test_failed_uses_top_level_errors(self) -> None: result = from_interaction( - Interaction.model_validate({ + parse_interaction({ 'id': '123', 'status': 'failed', 'errors': [{'code': '400', 'message': 'Invalid prompt format'}], @@ -1085,7 +1109,7 @@ def test_failed_uses_top_level_errors(self) -> None: def test_failed_content_block_is_a_blocked_output(self) -> None: result = from_interaction( - Interaction.model_validate({ + parse_interaction({ 'id': '123', 'status': 'failed', 'errors': [{'code': 'recitation', 'message': 'Recitation detected.'}], @@ -1098,7 +1122,7 @@ def test_failed_content_block_is_a_blocked_output(self) -> None: assert result.output.finish_message == 'Recitation detected.' def test_requires_action_exits_poll_loop(self) -> None: - interaction = Interaction.model_validate({ + interaction = parse_interaction({ 'id': '123', 'status': 'requires_action', 'steps': [{'type': 'model_output', 'content': [{'type': 'text', 'text': 'approve plan'}]}], @@ -1111,15 +1135,15 @@ def test_requires_action_exits_poll_loop(self) -> None: assert result.error.message == 'Background models do not support interrupts' def test_in_progress(self) -> None: - result = from_interaction(Interaction.model_validate({'id': '123', 'status': 'in_progress'})) + result = from_interaction(parse_interaction({'id': '123', 'status': 'in_progress'})) assert result.done is False def test_queued_keeps_polling(self) -> None: - result = from_interaction(Interaction.model_validate({'id': '123', 'status': 'queued'})) + result = from_interaction(parse_interaction({'id': '123', 'status': 'queued'})) assert result.done is False def test_completed_empty_steps_still_has_output(self) -> None: - result = from_interaction(Interaction.model_validate({'id': '123', 'status': 'completed', 'steps': []})) + result = from_interaction(parse_interaction({'id': '123', 'status': 'completed', 'steps': []})) assert result.done is True assert result.error is None assert result.output is not None @@ -1128,7 +1152,7 @@ def test_completed_empty_steps_still_has_output(self) -> None: assert result.output.message.content == [] def test_unknown_status_exits_poll_loop(self) -> None: - result = from_interaction(Interaction.model_validate({'id': '123', 'status': 'expired'})) + result = from_interaction(parse_interaction({'id': '123', 'status': 'expired'})) assert result.done is True assert result.output is None assert result.error is not None @@ -1136,7 +1160,7 @@ def test_unknown_status_exits_poll_loop(self) -> None: def test_incomplete_surfaces_partial_steps(self) -> None: result = from_interaction( - Interaction.model_validate({ + parse_interaction({ 'id': '123', 'status': 'incomplete', 'steps': [{'type': 'model_output', 'content': [{'type': 'text', 'text': 'partial'}]}], @@ -1153,14 +1177,14 @@ def test_incomplete_surfaces_partial_steps(self) -> None: assert result.output.message.metadata.get('interactionStatus') == 'incomplete' def test_incomplete_without_steps_errors(self) -> None: - result = from_interaction(Interaction.model_validate({'id': '123', 'status': 'incomplete'})) + result = from_interaction(parse_interaction({'id': '123', 'status': 'incomplete'})) assert result.done is True assert result.output is None assert result.error is not None def test_budget_exceeded_surfaces_partial_steps(self) -> None: result = from_interaction( - Interaction.model_validate({ + parse_interaction({ 'id': '123', 'status': 'budget_exceeded', 'steps': [{'type': 'model_output', 'content': [{'type': 'text', 'text': 'draft'}]}], @@ -1177,7 +1201,7 @@ def test_budget_exceeded_surfaces_partial_steps(self) -> None: assert result.output.message.metadata.get('interactionStatus') == 'budget_exceeded' def test_budget_exceeded_without_steps_errors(self) -> None: - result = from_interaction(Interaction.model_validate({'id': '123', 'status': 'budget_exceeded'})) + result = from_interaction(parse_interaction({'id': '123', 'status': 'budget_exceeded'})) assert result.done is True assert result.output is None assert result.error is not None @@ -1187,7 +1211,7 @@ def test_budget_exceeded_without_steps_errors(self) -> None: class TestFromInteractionSync: def test_failed_raises(self) -> None: with pytest.raises(GenkitError, match='Interaction failed') as raised: - from_interaction_sync(Interaction.model_validate({'status': 'failed'})) + from_interaction_sync(parse_interaction({'status': 'failed'})) assert raised.value.status == 'UNKNOWN' assert str(raised.value) == 'UNKNOWN: Interaction failed' @@ -1203,7 +1227,7 @@ def test_failed_raises(self) -> None: ) def test_failed_with_provider_code_is_classified(self, code: str, status: str) -> None: """A quota failure the server reported keeps its status so retry and fallback can act on it.""" - interaction = Interaction.model_validate({ + interaction = parse_interaction({ 'id': 'ix-1', 'status': 'failed', 'errors': [{'code': code, 'message': 'Quota exceeded for lyria'}], @@ -1214,7 +1238,7 @@ def test_failed_with_provider_code_is_classified(self, code: str, status: str) - assert isinstance(raised.value.__cause__, ValueError) def test_failed_step_error_grpc_code_is_classified(self) -> None: - interaction = Interaction.model_validate({ + interaction = parse_interaction({ 'id': 'ix-1', 'status': 'failed', 'steps': [{'type': 'model_output', 'error': {'code': 8, 'message': 'out of quota'}}], @@ -1226,7 +1250,7 @@ def test_failed_step_error_grpc_code_is_classified(self) -> None: @pytest.mark.parametrize('code', ['UNKNOWN', 'OK', '0', '2', '200', '999', 'SOMETHING_NEW', '']) def test_failed_with_unusable_code_is_unknown(self, code: str) -> None: """No real status from the server: UNKNOWN, which default Retry and Fallback leave alone.""" - interaction = Interaction.model_validate({ + interaction = parse_interaction({ 'id': 'ix-1', 'status': 'failed', 'errors': [{'code': code, 'message': 'model crashed'}], @@ -1238,7 +1262,7 @@ def test_failed_with_unusable_code_is_unknown(self, code: str) -> None: def test_returns_finish_reason_blocked_for_a_post_execution_safety_block(self) -> None: result = from_interaction_sync( - Interaction.model_validate({ + parse_interaction({ 'id': 'int-1', 'status': 'failed', 'errors': [{'code': 'safety', 'message': 'Response blocked due to safety violations.'}], @@ -1271,13 +1295,13 @@ def test_returns_finish_reason_blocked_for_a_post_execution_safety_block(self) - ) 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'}]}) + parse_interaction({'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({ + parse_interaction({ 'status': 'failed', 'errors': [{'code': 'safety', 'message': 'blocked'}], 'usage': { @@ -1304,7 +1328,7 @@ def test_raises_a_retryable_aborted_error_for_malformed_function_call(self) -> N 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({ + parse_interaction({ 'status': 'failed', 'errors': [{'code': 'malformed_function_call', 'message': advice}], }) @@ -1325,18 +1349,16 @@ def test_raises_a_retryable_aborted_error_for_malformed_function_call(self) -> N ) 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'}]}) - ) + from_interaction_sync(parse_interaction({'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'})) + from_interaction_sync(parse_interaction({'id': '123', 'status': 'queued'})) assert raised.value.status == 'FAILED_PRECONDITION' def test_requires_action_returns_pending_tool_requests_and_skips_resolved_sandbox_calls(self) -> None: - interaction = Interaction.model_validate({ + interaction = parse_interaction({ 'id': 'v1_abc123', 'status': 'requires_action', 'environment_id': 'env-123', @@ -1380,13 +1402,13 @@ def test_requires_action_returns_pending_tool_requests_and_skips_resolved_sandbo assert result.message.content[2].tool_request.input == {'dish': 'ramen'} def test_cancelled(self) -> None: - result = from_interaction_sync(Interaction.model_validate({'id': '123', 'status': 'cancelled'})) + result = from_interaction_sync(parse_interaction({'id': '123', 'status': 'cancelled'})) assert result.finish_reason == 'aborted' assert result.finish_message == 'Operation cancelled' def test_incomplete_surfaces_partial_steps(self) -> None: result = from_interaction_sync( - Interaction.model_validate({ + parse_interaction({ 'id': '123', 'status': 'incomplete', 'steps': [{'type': 'model_output', 'content': [{'type': 'text', 'text': 'partial'}]}], @@ -1399,11 +1421,11 @@ def test_incomplete_surfaces_partial_steps(self) -> None: def test_incomplete_without_steps_raises(self) -> None: with pytest.raises(ValueError, match='incomplete'): - from_interaction_sync(Interaction.model_validate({'id': '123', 'status': 'incomplete'})) + from_interaction_sync(parse_interaction({'id': '123', 'status': 'incomplete'})) def test_budget_exceeded_surfaces_partial_steps(self) -> None: result = from_interaction_sync( - Interaction.model_validate({ + parse_interaction({ 'id': '123', 'status': 'budget_exceeded', 'steps': [{'type': 'model_output', 'content': [{'type': 'text', 'text': 'draft'}]}], @@ -1414,12 +1436,12 @@ def test_budget_exceeded_surfaces_partial_steps(self) -> None: def test_in_progress_raises(self) -> None: with pytest.raises(GenkitError, match='still running') as raised: - from_interaction_sync(Interaction.model_validate({'id': '123', 'status': 'in_progress'})) + from_interaction_sync(parse_interaction({'id': '123', 'status': 'in_progress'})) assert raised.value.status == 'FAILED_PRECONDITION' def test_unknown_status_raises(self) -> None: with pytest.raises(ValueError, match='Unknown interaction status'): - from_interaction_sync(Interaction.model_validate({'id': '123', 'status': 'expired'})) + from_interaction_sync(parse_interaction({'id': '123', 'status': 'expired'})) class TestSplitSystemInstruction: @@ -1443,7 +1465,7 @@ def test_joins_multiple_system_turns(self) -> None: class TestUsageFromInteraction: def test_maps_totals_and_puts_modality_tokens_in_custom(self) -> None: - usage = Usage.model_validate({ + usage = UsageAdapter.validate_python({ 'total_input_tokens': 10, 'total_output_tokens': 4, 'total_tokens': 14, @@ -1465,7 +1487,7 @@ def test_maps_totals_and_puts_modality_tokens_in_custom(self) -> None: def test_text_and_image_tokens_are_not_characters_or_images(self) -> None: mapped = usage_from_interaction( - Usage.model_validate({ + UsageAdapter.validate_python({ 'total_input_tokens': 10, 'total_output_tokens': 0, 'total_tokens': 10, @@ -1481,7 +1503,7 @@ def test_text_and_image_tokens_are_not_characters_or_images(self) -> None: def test_reports_tool_use_tokens_in_custom(self) -> None: mapped = usage_from_interaction( - Usage.model_validate({ + UsageAdapter.validate_python({ 'total_input_tokens': 416, 'total_output_tokens': 393, 'total_tool_use_tokens': 2054, @@ -1494,7 +1516,7 @@ def test_reports_tool_use_tokens_in_custom(self) -> None: 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({ + UsageAdapter.validate_python({ 'total_tokens': 1011, 'total_tool_use_tokens': 0, 'grounding_tool_count': [ @@ -1506,7 +1528,7 @@ def test_reports_grounding_tool_counts_in_custom(self) -> None: 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})) + mapped = usage_from_interaction(UsageAdapter.validate_python({'total_input_tokens': 4, 'total_tokens': 4})) assert mapped.custom is None @@ -1523,7 +1545,7 @@ class TestWithBasicUsageStats: def test_adds_character_and_media_counts_next_to_the_token_counts(self) -> None: response = from_interaction_sync( - Interaction.model_validate({ + parse_interaction({ 'id': 'int-1', 'status': 'completed', 'steps': [ @@ -1565,10 +1587,276 @@ def test_adds_character_and_media_counts_next_to_the_token_counts(self) -> None: } 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'})) + response = from_interaction_sync(parse_interaction({'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 + + +def steps_of(*raw: dict[str, Any]) -> list[Step]: + """Validate wire steps the way a response is parsed.""" + return [StepAdapter.validate_python(step) for step in raw] + + +def parts_of(*raw: dict[str, Any], is_pending: bool = False) -> list[Part]: + """The Genkit parts for wire steps, in order.""" + return [part for step in steps_of(*raw) for part in from_interaction_step(step, is_pending=is_pending)] + + +class TestAgenticVideoProcessingSteps: + """Ported from the JS tests 'agentic video understanding' (shapes seen live on gemini-4-argon).""" + + processing_call: dict[str, Any] = {'type': 'processing_call', 'id': 'call_598332', 'signature': 'sig_call'} + processing_result: dict[str, Any] = { + 'type': 'processing_result', + 'call_id': 'call_598332', + 'signature': 'sig_result', + } + + def test_returns_processing_steps_as_custom_parts_with_their_signatures(self) -> None: + assert [part_dict(part) for part in parts_of(self.processing_call, self.processing_result)] == [ + {'custom': {'processingCall': {'id': 'call_598332'}}, 'metadata': {'thoughtSignature': 'sig_call'}}, + {'custom': {'processingResult': {'callId': 'call_598332'}}, 'metadata': {'thoughtSignature': 'sig_result'}}, + ] + + def test_resends_processing_steps_unchanged_in_the_history(self) -> None: + steps = to_interaction_steps([ + Message( + role='user', + content=[ + Part( + media=Media(url='https://www.youtube.com/watch?v=abc123'), + metadata={'processing': 'agentic'}, + ), + Part.from_text('What happens in this video?'), + ], + ), + Message( + role='model', + content=[ + *parts_of(self.processing_call, self.processing_result), + Part.from_text('The main moments are...'), + ], + ), + Message(role='user', content=[Part.from_text('What happens at the end?')]), + ]) + assert steps == [ + { + 'type': 'user_input', + 'content': [ + {'type': 'video', 'uri': 'https://www.youtube.com/watch?v=abc123', 'processing': 'agentic'}, + {'type': 'text', 'text': 'What happens in this video?'}, + ], + }, + self.processing_call, + self.processing_result, + {'type': 'model_output', 'content': [{'type': 'text', 'text': 'The main moments are...'}]}, + {'type': 'user_input', 'content': [{'type': 'text', 'text': 'What happens at the end?'}]}, + ] + + +CHANGELOG = 'https://ai.google.dev/gemini-api/docs/changelog' +PLACE = { + 'place_id': 'ChIJefTaTQZD04kRzuh2lpwlV-A', + 'name': 'Queen Victoria Park - Google Maps', + 'url': 'https://maps.google.com/maps?cid=16165430741939185870', +} +# Shapes seen live (Oct 2026): Google Maps on vertexAI gemini-3.8-flash (no +# arguments, no signature) and URL context on googleAI gemini-3.8-flash (with +# signatures). The other built-in tools are from the spec's examples. +MAPS_CALL: dict[str, Any] = {'type': 'google_maps_call', 'id': 'qpo3tzzp'} +MAPS_RESULT: dict[str, Any] = {'type': 'google_maps_result', 'call_id': 'qpo3tzzp', 'result': [{'places': [PLACE]}]} +URL_CALL: dict[str, Any] = { + 'type': 'url_context_call', + 'id': 'call_178104', + 'signature': 'sig_url_call', + 'arguments': {'urls': [CHANGELOG]}, +} +URL_RESULT: dict[str, Any] = { + 'type': 'url_context_result', + 'call_id': 'call_178104', + 'signature': 'sig_url_result', + 'result': [{'url': CHANGELOG, 'status': 'success'}], + 'is_error': False, +} +OTHER_BUILT_IN_STEPS: list[dict[str, Any]] = [ + {'type': 'file_search_call', 'id': 'file_call_1', 'signature': 'sig_f1'}, + {'type': 'file_search_result', 'call_id': 'file_call_1', 'signature': 'sig_f2'}, + { + 'type': 'mcp_server_tool_call', + 'id': 'mcp_call_1', + 'name': 'calculate_tax', + 'server_name': 'financial_mcp_server', + 'arguments': {'income': 120000, 'state': 'CA'}, + }, + { + 'type': 'mcp_server_tool_result', + 'call_id': 'mcp_call_1', + 'name': 'calculate_tax', + 'server_name': 'financial_mcp_server', + 'result': {'tax_due': 32400}, + }, +] +ALL_BUILT_IN_STEPS = [MAPS_CALL, MAPS_RESULT, URL_CALL, URL_RESULT, *OTHER_BUILT_IN_STEPS] + + +class TestServerSideBuiltInToolSteps: + """Ported from the JS tests 'server-side built-in tool steps'.""" + + def test_converts_google_maps_steps_into_custom_parts(self) -> None: + assert [part_dict(part) for part in parts_of(MAPS_CALL, MAPS_RESULT)] == [ + {'custom': {'googleMapsCall': {'id': 'qpo3tzzp'}}}, + {'custom': {'googleMapsResult': {'callId': 'qpo3tzzp', 'result': [{'places': [PLACE]}]}}}, + ] + + def test_converts_url_context_steps_into_custom_parts_with_their_signatures(self) -> None: + assert [part_dict(part) for part in parts_of(URL_CALL, URL_RESULT)] == [ + { + 'custom': {'urlContextCall': {'id': 'call_178104', 'arguments': {'urls': [CHANGELOG]}}}, + 'metadata': {'thoughtSignature': 'sig_url_call'}, + }, + { + 'custom': { + 'urlContextResult': { + 'callId': 'call_178104', + 'result': [{'url': CHANGELOG, 'status': 'success'}], + 'isError': False, + } + }, + 'metadata': {'thoughtSignature': 'sig_url_result'}, + }, + ] + + def test_never_produces_tool_requests(self) -> None: + # Even with is_pending, which turns client function calls into tool + # requests: the server already ran these tools. + parts = parts_of(*ALL_BUILT_IN_STEPS, is_pending=True) + assert len(parts) == len(ALL_BUILT_IN_STEPS) + assert all(part.tool_request is None for part in parts) + assert all('unknownStep' not in (part.custom or {}) for part in parts) + + def test_sends_every_built_in_tool_step_back_unchanged_in_the_history(self) -> None: + history = [ + Message(role='user', content=[Part.from_text('Name two sights near me.')]), + Message( + role='model', + content=[*parts_of(*ALL_BUILT_IN_STEPS), Part.from_text('Queen Victoria Park.')], + ), + Message(role='user', content=[Part.from_text('Which one is closer?')]), + ] + assert to_interaction_steps(history) == [ + {'type': 'user_input', 'content': [{'type': 'text', 'text': 'Name two sights near me.'}]}, + *ALL_BUILT_IN_STEPS, + {'type': 'model_output', 'content': [{'type': 'text', 'text': 'Queen Victoria Park.'}]}, + {'type': 'user_input', 'content': [{'type': 'text', 'text': 'Which one is closer?'}]}, + ] + + def test_keeps_the_custom_parts_in_the_final_response(self) -> None: + result = from_interaction_sync( + parse_interaction({ + 'status': 'completed', + 'steps': [ + MAPS_CALL, + MAPS_RESULT, + {'type': 'model_output', 'content': [{'type': 'text', 'text': 'Queen Victoria Park.'}]}, + ], + }) + ) + assert result.message is not None + custom_keys = [key for part in result.message.content for key in (part.custom or {})] + assert custom_keys == ['googleMapsCall', 'googleMapsResult'] + + def test_round_trips_google_search_steps_without_arguments_or_result(self) -> None: + # Seen live on vertexAI (gemini-3.8-flash): the platform sent these + # steps without `arguments` / `result`. + search_call = {'type': 'google_search_call', 'id': 'ssg39wjg', 'search_type': 'web_search'} + search_result = {'type': 'google_search_result', 'call_id': 'ssg39wjg', 'is_error': False} + assert [part_dict(part) for part in parts_of(search_call, search_result)] == [ + {'custom': {'googleSearchCall': {'id': 'ssg39wjg', 'searchType': 'web_search'}}}, + {'custom': {'googleSearchResult': {'callId': 'ssg39wjg', 'isError': False}}}, + ] + history = [ + Message(role='user', content=[Part.from_text('Read the changelog.')]), + Message( + role='model', + content=[*parts_of(search_call, search_result), Part.from_text('October 13, 2026.')], + ), + Message(role='user', content=[Part.from_text('And the entry before?')]), + ] + steps = to_interaction_steps(history) + # Sent back as received: no empty arguments or result added. + assert steps[1] == search_call + assert steps[2] == search_result + + def test_round_trips_built_in_tool_steps_with_only_their_ids(self) -> None: + # The platform can omit fields the spec marks as required; only the + # ids are needed to round-trip (the SDK types used to fill in + # `arguments: {}` / `result: {}` here). + bare_steps: list[dict[str, Any]] = [ + {'type': 'url_context_call', 'id': 'u1'}, + {'type': 'url_context_result', 'call_id': 'u1'}, + {'type': 'google_maps_call', 'id': 'm1'}, + {'type': 'google_maps_result', 'call_id': 'm1'}, + {'type': 'mcp_server_tool_call', 'id': 'p1'}, + {'type': 'mcp_server_tool_result', 'call_id': 'p1'}, + ] + history = [Message(role='model', content=parts_of(*bare_steps))] + assert to_interaction_steps(history) == bare_steps + + def test_accepts_an_empty_trailing_model_output_step(self) -> None: + # Seen live on vertexAI (Google Maps, store: true). + result = from_interaction_sync( + parse_interaction({ + 'status': 'completed', + 'steps': [ + {'type': 'thought', 'signature': 'sig_thought'}, + {'type': 'model_output', 'content': [{'type': 'text', 'text': 'Queen Victoria Park.'}]}, + MAPS_CALL, + MAPS_RESULT, + {'type': 'model_output'}, + ], + }) + ) + assert result.message is not None + content = result.message.content + assert len(content) == 4 + assert content[1].text == 'Queen Victoria Park.' + assert 'googleMapsCall' in (content[2].custom or {}) + assert 'googleMapsResult' in (content[3].custom or {}) + + +class TestSavedUnknownSteps: + """Steps stored as ``unknownStep`` by older plugin versions are still resent.""" + + def test_resends_an_old_built_in_tool_step_without_the_none_fields_the_sdk_added(self) -> None: + # Older versions stored the SDK's model_dump(): `result: None` was + # never sent by the server. + saved = {'type': 'url_context_result', 'call_id': 'u1', 'result': None, 'signature': 'sig'} + history = [Message(role='model', content=[Part.from_custom({'unknownStep': saved})])] + assert to_interaction_steps(history) == [{'type': 'url_context_result', 'call_id': 'u1', 'signature': 'sig'}] + + def test_drops_none_fields_at_every_level(self) -> None: + saved = {'type': 'future_step', 'data': {'kept': 1, 'gone': None}, 'top': None} + history = [Message(role='model', content=[Part.from_custom({'unknownStep': saved})])] + assert to_interaction_steps(history) == [{'type': 'future_step', 'data': {'kept': 1}}] + + +class TestResponseKeepsTheInteractionAsSent: + def test_raw_is_the_interaction_as_received_and_custom_is_not_set(self) -> None: + body = { + 'id': 'v1_abc123', + 'status': 'completed', + 'steps': [ + {'type': 'url_context_call', 'id': 'u1'}, + {'type': 'model_output', 'content': [{'type': 'text', 'text': 'Done.'}]}, + ], + } + result = from_interaction_sync(parse_interaction(body)) + # Nothing filled in (the SDK types added `arguments: {}` and nulls). + assert result.raw == body + # Genkit deprecates the response-level `custom` in favor of `raw`, so + # the interaction isn't copied there (Genkit core defaults it to {}). + assert not result.custom diff --git a/packages/genkit-google-genai/tests/interactions/interactions_models_test.py b/packages/genkit-google-genai/tests/interactions/interactions_models_test.py index de2aead3d..099b44270 100644 --- a/packages/genkit-google-genai/tests/interactions/interactions_models_test.py +++ b/packages/genkit-google-genai/tests/interactions/interactions_models_test.py @@ -26,6 +26,7 @@ from genkit_google_genai._google import GenaiModels, GoogleAI, VertexAI, googleai_name from genkit_google_genai._interactions._converters import split_system_instruction from genkit_google_genai._interactions._options import ClientOptions +from genkit_google_genai._interactions._types import GeminiInteraction, parse_interaction from genkit_google_genai._models._antigravity import AntigravityConfig, create_antigravity_action from genkit_google_genai._models._deep_research import ( DeepResearchConfig, @@ -35,7 +36,6 @@ from genkit_google_genai._models._interactions_lyria import LyriaConfig, create_lyria_action from genkit_google_genai._models._interactions_registry import deep_research_model_info, lyria_model_info from genkit_google_genai._models._interactions_utils import pop_extra -from google.genai.interactions import Interaction from pydantic import BaseModel, ValidationError from genkit import Genkit, GenkitError, Message, Operation, Part, Role @@ -87,37 +87,37 @@ async def create( api_key: str, body: dict[str, Any], client_options: ClientOptions | None = None, - ) -> Interaction: + ) -> GeminiInteraction: create_calls.append(body) if captured is not None: captured['create'] = body captured['api_key'] = api_key captured['client_options'] = client_options - return Interaction.model_validate(create_result or {'id': 'ix-1', 'status': 'in_progress'}) + return parse_interaction(create_result or {'id': 'ix-1', 'status': 'in_progress'}) async def get( api_key: str, interaction_id: str, client_options: ClientOptions | None = None, - ) -> Interaction: + ) -> GeminiInteraction: get_calls.append(interaction_id) if captured is not None: captured['get'] = interaction_id captured['api_key'] = api_key captured['client_options'] = client_options - return Interaction.model_validate(get_result or {'id': interaction_id, 'status': 'completed', 'steps': []}) + return parse_interaction(get_result or {'id': interaction_id, 'status': 'completed', 'steps': []}) async def cancel( api_key: str, interaction_id: str, client_options: ClientOptions | None = None, - ) -> Interaction: + ) -> GeminiInteraction: cancel_calls.append(interaction_id) if captured is not None: captured['cancel'] = interaction_id captured['api_key'] = api_key captured['client_options'] = client_options - return Interaction.model_validate(cancel_result or {'id': interaction_id, 'status': 'cancelled'}) + return parse_interaction(cancel_result or {'id': interaction_id, 'status': 'cancelled'}) patches: dict[str, Any] = { 'create_interaction': AsyncMock(side_effect=create), @@ -1821,12 +1821,12 @@ async def lookup_allergens(query: _AllergenInput) -> dict[str, list[str]]: create_calls: list[dict[str, Any]] = [] replies = [ - Interaction.model_validate(turn_1), - Interaction.model_validate(turn_2), - Interaction.model_validate(_TEXT_REPLY), + parse_interaction(turn_1), + parse_interaction(turn_2), + parse_interaction(_TEXT_REPLY), ] - async def fake_create(_api_key: str, kwargs: dict[str, Any], _options: object) -> Interaction: + async def fake_create(_api_key: str, kwargs: dict[str, Any], _options: object) -> GeminiInteraction: create_calls.append(kwargs) return replies.pop(0) diff --git a/packages/genkit-google-genai/tests/interactions/interactions_types_test.py b/packages/genkit-google-genai/tests/interactions/interactions_types_test.py new file mode 100644 index 000000000..c55667740 --- /dev/null +++ b/packages/genkit-google-genai/tests/interactions/interactions_types_test.py @@ -0,0 +1,134 @@ +# 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 plugin's own Interactions wire types (parsing and open unions).""" + +from __future__ import annotations + +import pytest +from genkit_google_genai._interactions._types import ( + CONTENT_ADAPTER, + STEP_ADAPTER, + UnknownContent, + UnknownSseEvent, + UnknownStep, + UnknownStepDelta, + UnknownTextAnnotation, + parse_interaction, + parse_sse_event, +) +from pydantic import ValidationError + + +class TestParseInteraction: + def test_keeps_exactly_what_the_server_sent(self) -> None: + body = { + 'id': 'v1_abc123', + 'status': 'completed', + 'steps': [ + {'type': 'url_context_call', 'id': 'u1'}, + {'type': 'mcp_server_tool_result', 'call_id': 'm1'}, + {'type': 'model_output', 'content': [{'type': 'text', 'text': 'Hi'}]}, + ], + 'usage': {'total_tokens': 5}, + } + # Nothing is filled in (the SDK added `arguments: {}`, `result: {}`). + assert parse_interaction(body) == body + + def test_keeps_fields_the_types_do_not_list(self) -> None: + body = { + 'status': 'completed', + 'new_top_level_field': {'a': 1}, + 'steps': [{'type': 'google_search_call', 'id': 'g1', 'new_step_field': True}], + } + assert parse_interaction(body) == body + + def test_keeps_an_unknown_step_type_as_sent(self) -> None: + future = {'type': 'future_step', 'payload': {'x': [1, 2]}} + parsed = parse_interaction({'status': 'completed', 'steps': [future]}) + steps = parsed.get('steps') or [] + assert steps == [future] + assert isinstance(steps[0], UnknownStep) + + def test_keeps_a_known_step_with_mismatched_fields_as_unknown(self) -> None: + odd = {'type': 'url_context_call', 'id': 'u1', 'arguments': 'not an object'} + parsed = parse_interaction({'status': 'completed', 'steps': [odd]}) + steps = parsed.get('steps') or [] + assert steps == [odd] + assert isinstance(steps[0], UnknownStep) + + def test_known_step_is_not_unknown(self) -> None: + step = STEP_ADAPTER.validate_python({'type': 'processing_call', 'id': 'p1', 'signature': 'c2ln'}) + assert not isinstance(step, UnknownStep) + assert step['type'] == 'processing_call' + + def test_keeps_unknown_content_inside_a_known_step(self) -> None: + step = STEP_ADAPTER.validate_python({ + 'type': 'model_output', + 'content': [{'type': 'hologram', 'data': 'x'}, {'type': 'text', 'text': 'ok'}], + }) + assert not isinstance(step, UnknownStep) + assert step['type'] == 'model_output' + content = step.get('content') or [] + assert isinstance(content[0], UnknownContent) + assert not isinstance(content[1], UnknownContent) + + def test_keeps_unknown_text_annotations(self) -> None: + content = CONTENT_ADAPTER.validate_python({ + 'type': 'text', + 'text': 'hi', + 'annotations': [{'type': 'future_citation', 'x': 1}, {'type': 'url_citation', 'url': 'https://a.b'}], + }) + assert not isinstance(content, UnknownContent) + assert content['type'] == 'text' + annotations = content.get('annotations') or [] + assert isinstance(annotations[0], UnknownTextAnnotation) + assert not isinstance(annotations[1], UnknownTextAnnotation) + assert content == { + 'type': 'text', + 'text': 'hi', + 'annotations': [{'type': 'future_citation', 'x': 1}, {'type': 'url_citation', 'url': 'https://a.b'}], + } + + def test_raises_for_a_body_that_is_not_an_interaction(self) -> None: + with pytest.raises(ValidationError): + parse_interaction(['not', 'an', 'object']) + with pytest.raises(ValidationError): + parse_interaction({'steps': 'not a list'}) + + def test_raises_for_a_step_without_a_type(self) -> None: + with pytest.raises(ValidationError): + parse_interaction({'steps': [{'id': 'no-type'}]}) + + +class TestParseSseEvent: + def test_parses_a_step_delta_event(self) -> None: + event = parse_sse_event({'event_type': 'step.delta', 'index': 0, 'delta': {'type': 'text', 'text': 'Hi'}}) + assert not isinstance(event, UnknownSseEvent) + assert event['event_type'] == 'step.delta' + delta = event.get('delta') + assert delta is not None and not isinstance(delta, UnknownStepDelta) + assert delta == {'type': 'text', 'text': 'Hi'} + + def test_keeps_unknown_events_and_deltas(self) -> None: + event = parse_sse_event({'event_type': 'future.event', 'x': 1}) + assert isinstance(event, UnknownSseEvent) + assert event == {'event_type': 'future.event', 'x': 1} + delta_event = parse_sse_event({'event_type': 'step.delta', 'index': 1, 'delta': {'type': 'future_delta'}}) + assert not isinstance(delta_event, UnknownSseEvent) + assert delta_event['event_type'] == 'step.delta' + delta = delta_event.get('delta') + assert isinstance(delta, UnknownStepDelta)