mirror of
https://github.com/livekit/agents.git
synced 2026-12-06 03:18:30 +00:00
Migrate provider WebSocket handling to shared typed protocols, pooling, pacing, and idle timers. Preserve SmallestAI continuations with response-based silence completion and isolated segments. Keep connection acquisition, reconnect controls, stream cleanup, and host wrapper ownership safe across cancellation. Consolidate provider interfaces and typed MCP contracts. Normalize pending speech boundaries and preserve conversation identity, ordering, late results, and acknowledged checkpoints across overlapping voice runs. Extend deterministic regressions, storage observations, and lifecycle documentation. Validation: rebuilt extension; 2900 Python tests passed; formatting, lint, and type checks passed. Rust, binding, codegen, and deterministic simulation checks are recorded in the audit and lifecycle verification records.
432 lines
16 KiB
Python
432 lines
16 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import re
|
|
from collections.abc import Mapping, Sequence, Set
|
|
from copy import deepcopy
|
|
from dataclasses import dataclass
|
|
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, APIError, 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) -> APIError:
|
|
sdk_error = cast(APICallError, error)
|
|
if sdk_error.code is None:
|
|
# an api_core error without an HTTP status: the service failed in an unknown way
|
|
return APIError(sdk_error.message, kind="server", body=sdk_error.details)
|
|
return APIStatusError(sdk_error.message, status_code=sdk_error.code, 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)
|
|
|
|
_CLOUD_PLATFORM_SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GeminiBackend:
|
|
"""Where a Gemini request goes: the Gemini API with a key, or Vertex AI with a project."""
|
|
|
|
vertexai: bool
|
|
api_key: str | None
|
|
project: str | None
|
|
location: str | None
|
|
credentials: Credentials | None
|
|
|
|
|
|
def gemini_backend(
|
|
*,
|
|
api_key: NotGivenOr[str],
|
|
vertexai: NotGivenOr[bool],
|
|
project: NotGivenOr[str],
|
|
location: NotGivenOr[str],
|
|
credentials: NotGivenOr[Credentials],
|
|
credentials_info: NotGivenOr[Mapping[str, object]],
|
|
credentials_file: NotGivenOr[str],
|
|
default_location: str,
|
|
) -> GeminiBackend:
|
|
"""Resolve the Gemini backend from the arguments, then the environment.
|
|
|
|
`GOOGLE_API_KEY` supplies the key, and `GOOGLE_GENAI_USE_VERTEXAI` picks Vertex AI. Without
|
|
either, explicit credentials, a project or a location pick Vertex AI. On Vertex AI the
|
|
project comes from `project`, `GOOGLE_CLOUD_PROJECT`, the credentials, or Application
|
|
Default Credentials, and the location from `location` or `GOOGLE_CLOUD_LOCATION`.
|
|
"""
|
|
key = api_key if is_given(api_key) else os.environ.get("GOOGLE_API_KEY")
|
|
creds: Credentials | None = None
|
|
creds_project: str | None = None
|
|
if is_given(credentials):
|
|
creds = credentials
|
|
elif is_given(credentials_info):
|
|
creds, creds_project = auth.load_credentials_from_dict(
|
|
credentials_info, scopes=_CLOUD_PLATFORM_SCOPES
|
|
)
|
|
elif is_given(credentials_file):
|
|
creds, creds_project = auth.load_credentials_from_file(
|
|
credentials_file, scopes=_CLOUD_PLATFORM_SCOPES
|
|
)
|
|
|
|
if is_given(vertexai):
|
|
use_vertexai = vertexai
|
|
elif "GOOGLE_GENAI_USE_VERTEXAI" in os.environ:
|
|
use_vertexai = os.environ["GOOGLE_GENAI_USE_VERTEXAI"].lower() in ("true", "1")
|
|
else:
|
|
use_vertexai = not is_given(api_key) and (
|
|
creds is not None or is_given(project) or is_given(location)
|
|
)
|
|
|
|
if not use_vertexai:
|
|
if creds is not None:
|
|
raise ValueError("credentials authenticate Vertex AI only; pass vertexai=True")
|
|
if not key:
|
|
raise ValueError(
|
|
"a Gemini API key is required: pass api_key or set GOOGLE_API_KEY, or use "
|
|
"Vertex AI with vertexai=True"
|
|
)
|
|
return GeminiBackend(
|
|
vertexai=False, api_key=key, project=None, location=None, credentials=None
|
|
)
|
|
|
|
gcp_project = (
|
|
project if is_given(project) else os.environ.get("GOOGLE_CLOUD_PROJECT") or creds_project
|
|
)
|
|
if not gcp_project:
|
|
_, gcp_project = auth.default(scopes=_CLOUD_PLATFORM_SCOPES)
|
|
if not gcp_project:
|
|
raise ValueError(
|
|
"a Google Cloud project is required for Vertex AI: pass project or set "
|
|
"GOOGLE_CLOUD_PROJECT"
|
|
)
|
|
return GeminiBackend(
|
|
vertexai=True,
|
|
api_key=None,
|
|
project=gcp_project,
|
|
location=location
|
|
if is_given(location)
|
|
else os.environ.get("GOOGLE_CLOUD_LOCATION") or default_location,
|
|
credentials=creds,
|
|
)
|
|
|
|
|
|
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
|