from __future__ import annotations import re from collections.abc import Mapping, Sequence, Set from copy import deepcopy from types import GenericAlias, UnionType from typing import Any, ClassVar, Protocol, TypeVar, cast from pydantic import TypeAdapter, ValidationError from pydantic.alias_generators import to_camel import google.auth from google.api_core.client_options import ClientOptions from google.api_core.exceptions import GoogleAPICallError from google.auth.credentials import Credentials from google.genai import types from livekit.agents import APIConnectOptions, APIStatusError, llm from livekit.agents.types import NOT_GIVEN, NotGivenOr from livekit.agents.utils import is_given from .log import logger from .tools import GeminiTool class Auth(Protocol): """Typed boundary for google-auth's credential resolvers.""" def default(self, *, scopes: Sequence[str] | None = None) -> tuple[Credentials, str | None]: ... def load_credentials_from_file( self, filename: str, *, scopes: Sequence[str] | None = None ) -> tuple[Credentials, str | None]: ... def load_credentials_from_dict( self, info: Mapping[str, object], *, scopes: Sequence[str] | None = None ) -> tuple[Credentials, str | None]: ... class APICallError(Protocol): message: str code: int | None @property def details(self) -> list[object]: ... def api_status_error(error: GoogleAPICallError) -> APIStatusError: sdk_error = cast(APICallError, error) return APIStatusError( sdk_error.message, status_code=sdk_error.code or -1, body=sdk_error.details ) ClientT = TypeVar("ClientT", covariant=True) class ServiceAccountClient(Protocol[ClientT]): def from_service_account_info( self, info: Mapping[str, object], *, client_options: ClientOptions | None = None ) -> ClientT: ... auth = cast(Auth, google.auth) ResponseSchema = types.Schema | dict[str, object] | type[object] | GenericAlias | UnionType __all__ = ["create_tools_config"] def create_tools_config( tool_ctx: llm.ToolContext, *, tool_behavior: NotGivenOr[types.Behavior] = NOT_GIVEN, use_parameters_json_schema: bool = True, allow_mixed_tools: bool = True, ) -> tuple[list[types.Tool], bool]: """Build the Gemini tools list. Returns ``(tools, mixed)`` where ``mixed`` is True when both function tools and provider (built-in) tools were emitted together — the single source of truth the caller uses to enable ``include_server_side_tool_invocations``. """ gemini_tools: list[types.Tool] = [] function_tools: list[types.FunctionDeclaration] = [] for schema in tool_ctx.parse_function_tools( "google", tool_behavior=tool_behavior.value if tool_behavior else None, use_parameters_json_schema=use_parameters_json_schema, ): try: function_tools.append(types.FunctionDeclaration.model_validate(schema)) except ValidationError as e: raise ValueError(f"tool {schema.get('name')} has a schema Gemini rejected") from e if function_tools: gemini_tools.append(types.Tool(function_declarations=function_tools)) provider_tools = [tool for tool in tool_ctx.provider_tools if isinstance(tool, GeminiTool)] # generateContent only supports combining built-in tools with function tools on the # Gemini 3 Developer API: https://ai.google.dev/gemini-api/docs/tool-combination if function_tools and provider_tools and not allow_mixed_tools: logger.warning( "ignoring provider tools; combining them with function tools requires the " "Gemini 3 Developer API (Vertex AI is not supported)" ) return gemini_tools, False # only convert tools we actually send, so a dropped tool can't break the request gemini_tools.extend(tool.to_tool_config() for tool in provider_tools) return gemini_tools, bool(function_tools and provider_tools) def create_function_response( output: llm.FunctionCallOutput, *, vertexai: bool = False, tool_response_scheduling: NotGivenOr[types.FunctionResponseScheduling] = NOT_GIVEN, send_id: bool = True, ) -> types.FunctionResponse: # the id is sent on both APIs: gemini-3.8-live on Vertex AI silently drops a response to a # BLOCKING call that carries no id, and never replies. it is left out when the server issued # no id for the call, since one we made up locally would name a call the server never made res = types.FunctionResponse( id=output.call_id if send_id else None, name=output.name, response={"error": output.output} if output.is_error else {"output": output.output}, ) # vertexai does not support scheduling; the gemini api defaults it to WHEN_IDLE if not vertexai and is_given(tool_response_scheduling): res.scheduling = tool_response_scheduling return res def get_tool_results_for_realtime( chat_ctx: llm.ChatContext, *, vertexai: bool = False, tool_response_scheduling: NotGivenOr[types.FunctionResponseScheduling] = NOT_GIVEN, supports_silent_scheduling: bool = False, synthetic_call_ids: Set[str] = frozenset(), ) -> types.LiveClientToolResponse | None: """Build the tool responses, SILENT for outputs that want no reply. SILENT is claimed only where the session honours it; see `_RealtimeOptions.tool_behavior`. Calls in `synthetic_call_ids` had no server-issued id, so their responses carry none. """ function_responses = [ create_function_response( msg, vertexai=vertexai, tool_response_scheduling=( types.FunctionResponseScheduling.SILENT if supports_silent_scheduling and not msg.reply_required else tool_response_scheduling ), send_id=msg.call_id not in synthetic_call_ids, ) for msg in chat_ctx.items if msg.type == "function_call_output" ] return ( types.LiveClientToolResponse(function_responses=function_responses) if function_responses else None ) def to_response_format(response_format: ResponseSchema) -> types.Schema | dict[str, object] | None: if isinstance(response_format, types.Schema): return response_format if isinstance(response_format, dict): schema = response_format else: schema = TypeAdapter(response_format).json_schema() return _GeminiJsonSchema(schema).simplify() class _GeminiJsonSchema: """ Transforms the JSON Schema from Pydantic to be suitable for Gemini. based on pydantic-ai implementation https://github.com/pydantic/pydantic-ai/blob/085a9542a7360b7e388ce575323ce189b397d7ad/pydantic_ai_slim/pydantic_ai/models/gemini.py#L809 """ # Type mapping from JSON Schema to Gemini Schema TYPE_MAPPING: dict[str, types.Type] = { "string": types.Type.STRING, "number": types.Type.NUMBER, "integer": types.Type.INTEGER, "boolean": types.Type.BOOLEAN, "array": types.Type.ARRAY, "object": types.Type.OBJECT, } def __init__(self, schema: dict[str, Any]): self.schema = deepcopy(schema) self.defs = self.schema.pop("$defs", {}) def simplify(self) -> dict[str, Any] | None: self._simplify(self.schema, refs_stack=()) # If the schema is an OBJECT with no properties, return None. if self.schema.get("type") == types.Type.OBJECT and not self.schema.get("properties"): return None return self.schema # every key types.Schema accepts (field name plus its camelCase alias), together with # the JSON Schema keywords this transformer still has to read itself. types.Schema is # declared extra="forbid", so any other keyword -- readOnly, deprecated, $comment, # x-google-* and other vendor extensions -- survives simplify() only to fail # validation later when the FunctionDeclaration is built. `const` is kept because the # conversion below turns it into the single-value `enum` Gemini does support. _ALLOWED_KEYS: ClassVar[frozenset[str]] = frozenset( set(types.Schema.model_fields) | {to_camel(name) for name in types.Schema.model_fields} | {"anyOf", "$ref", "prefixItems", "const"} ) def _simplify(self, schema: dict[str, Any], refs_stack: tuple[str, ...]) -> None: for key in [k for k in schema if k not in self._ALLOWED_KEYS]: logger.debug(f"dropping unsupported JSON Schema keyword: {key}") schema.pop(key, None) schema.pop("title", None) schema.pop("default", None) schema.pop("additionalProperties", None) schema.pop("$schema", None) if (const := schema.pop("const", None)) is not None: # Gemini doesn't support const, but it does support enum with a single value schema["enum"] = [const] schema.pop("discriminator", None) schema.pop("examples", None) if ref := schema.pop("$ref", None): key = re.sub(r"^#/\$defs/", "", ref) if key in refs_stack: raise ValueError("Recursive `$ref`s in JSON Schema are not supported by Gemini") refs_stack += (key,) schema_def = self.defs[key] self._simplify(schema_def, refs_stack) schema.update(schema_def) return if "enum" in schema and "type" not in schema: schema["type"] = self._infer_type(schema["enum"][0]) # Convert type value to Gemini format if "type" in schema and schema["type"] != "null": json_type = schema["type"] if json_type in self.TYPE_MAPPING: schema["type"] = self.TYPE_MAPPING[json_type] elif isinstance(json_type, types.Type): schema["type"] = json_type else: raise ValueError(f"Unsupported type in JSON Schema: {json_type}") # Map field names that differ between JSON Schema and Gemini self._map_field_names(schema) # Handle anyOf - map to any_of if any_of := schema.pop("anyOf", None): if any_of: mapped_any_of: list[dict[str, Any]] = [] has_null = False non_null_schema = None for item_schema in any_of: self._simplify(item_schema, refs_stack) if item_schema == {"type": "null"}: has_null = True else: non_null_schema = item_schema mapped_any_of.append(item_schema) if has_null and len(any_of) == 2 and non_null_schema: schema.update(non_null_schema) schema["nullable"] = True else: schema["any_of"] = mapped_any_of type_ = schema.get("type") if type_ == types.Type.OBJECT: self._object(schema, refs_stack) elif type_ == types.Type.ARRAY: self._array(schema, refs_stack) def _infer_type(self, value: Any) -> str: if isinstance(value, int): return "integer" elif isinstance(value, float): return "number" elif isinstance(value, str): return "string" elif isinstance(value, bool): return "boolean" else: raise ValueError(f"Unsupported type in Schema: {type(value)}") def _map_field_names(self, schema: dict[str, Any]) -> None: """Map JSON Schema field names to Gemini Schema field names.""" mappings = { "minLength": "min_length", "maxLength": "max_length", "minItems": "min_items", "maxItems": "max_items", "minProperties": "min_properties", "maxProperties": "max_properties", } for json_name, gemini_name in mappings.items(): if json_name in schema: schema[gemini_name] = schema.pop(json_name) def _object(self, schema: dict[str, Any], refs_stack: tuple[str, ...]) -> None: if properties := schema.get("properties"): for value in properties.values(): self._simplify(value, refs_stack) if "property_ordering" not in schema and "propertyOrdering" not in schema: schema["property_ordering"] = list(properties) def _array(self, schema: dict[str, Any], refs_stack: tuple[str, ...]) -> None: if prefix_items := schema.get("prefixItems"): for prefix_item in prefix_items: self._simplify(prefix_item, refs_stack) if items_schema := schema.get("items"): self._simplify(items_schema, refs_stack) def genai_http_options( options: APIConnectOptions, http_options: types.HttpOptions | None ) -> types.HttpOptions: result = http_options.model_copy() if http_options is not None else types.HttpOptions() result.headers = dict(result.headers or {}) result.timeout = 0 result.retry_options = types.HttpRetryOptions(attempts=1) return result