Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

[Feat] New Endpoint - Google Interactions API - added on litellm SDK (#18079)

Ishaan Jaffc727c8216fda
diff --git a/litellm/__init__.py b/litellm/__init__.py
index e1719f13263..b71240777f9 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -1240,6 +1240,7 @@ from .llms.xai.responses.transformation import XAIResponsesAPIConfig
from .llms.litellm_proxy.responses.transformation import (
LiteLLMProxyResponsesAPIConfig,
)
+from .llms.gemini.interactions.transformation import GoogleAIStudioInteractionsConfig
from .llms.openai.chat.o_series_transformation import (
OpenAIOSeriesConfig as OpenAIO1Config, # maintain backwards compatibility
OpenAIOSeriesConfig,
@@ -1402,6 +1403,9 @@ from .batch_completion.main import * # type: ignore
from .rerank_api.main import *
from .llms.anthropic.experimental_pass_through.messages.handler import *
from .responses.main import *
+# Interactions API is available as litellm.interactions module
+# Usage: litellm.interactions.create(), litellm.interactions.get(), etc.
+from . import interactions
from .skills.main import (
create_skill,
acreate_skill,
diff --git a/litellm/interactions/__init__.py b/litellm/interactions/__init__.py
new file mode 100644
index 00000000000..e1125b649a6
--- /dev/null
+++ b/litellm/interactions/__init__.py
@@ -0,0 +1,68 @@
+"""
+LiteLLM Interactions API
+
+This module provides SDK methods for Google's Interactions API.
+
+Usage:
+ import litellm
+
+ # Create an interaction with a model
+ response = litellm.interactions.create(
+ model="gemini-2.5-flash",
+ input="Hello, how are you?"
+ )
+
+ # Create an interaction with an agent
+ response = litellm.interactions.create(
+ agent="deep-research-pro-preview-12-2025",
+ input="Research the current state of cancer research"
+ )
+
+ # Async version
+ response = await litellm.interactions.acreate(...)
+
+ # Get an interaction
+ response = litellm.interactions.get(interaction_id="...")
+
+ # Delete an interaction
+ result = litellm.interactions.delete(interaction_id="...")
+
+ # Cancel an interaction
+ result = litellm.interactions.cancel(interaction_id="...")
+
+Methods:
+- create(): Sync create interaction
+- acreate(): Async create interaction
+- get(): Sync get interaction
+- aget(): Async get interaction
+- delete(): Sync delete interaction
+- adelete(): Async delete interaction
+- cancel(): Sync cancel interaction
+- acancel(): Async cancel interaction
+"""
+
+from litellm.interactions.main import (
+ acancel,
+ acreate,
+ adelete,
+ aget,
+ cancel,
+ create,
+ delete,
+ get,
+)
+
+__all__ = [
+ # Create
+ "create",
+ "acreate",
+ # Get
+ "get",
+ "aget",
+ # Delete
+ "delete",
+ "adelete",
+ # Cancel
+ "cancel",
+ "acancel",
+]
diff --git a/litellm/interactions/http_handler.py b/litellm/interactions/http_handler.py
new file mode 100644
index 00000000000..76aae6d5d49
--- /dev/null
+++ b/litellm/interactions/http_handler.py
@@ -0,0 +1,714 @@
+"""
+HTTP Handler for Interactions API requests.
+
+This module handles the HTTP communication for the Google Interactions API.
+"""
+
+import json
+from typing import (
+ Any,
+ AsyncIterator,
+ Coroutine,
+ Dict,
+ Iterator,
+ Optional,
+ Union,
+)
+
+import httpx
+
+import litellm
+from litellm._logging import verbose_logger
+from litellm.constants import request_timeout
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.llms.base_llm.interactions.transformation import BaseInteractionsAPIConfig
+from litellm.llms.custom_httpx.http_handler import (
+ AsyncHTTPHandler,
+ HTTPHandler,
+ _get_httpx_client,
+ get_async_httpx_client,
+)
+from litellm.types.interactions import (
+ CancelInteractionResult,
+ DeleteInteractionResult,
+ InteractionInput,
+ InteractionsAPIOptionalRequestParams,
+ InteractionsAPIResponse,
+ InteractionsAPIStreamingResponse,
+)
+from litellm.types.router import GenericLiteLLMParams
+
+
+class InteractionsHTTPHandler:
+ """
+ HTTP handler for Interactions API requests.
+ """
+
+ def _handle_error(
+ self,
+ e: Exception,
+ provider_config: BaseInteractionsAPIConfig,
+ ) -> Exception:
+ """Handle errors from HTTP requests."""
+ if isinstance(e, httpx.HTTPStatusError):
+ error_message = e.response.text
+ status_code = e.response.status_code
+ headers = dict(e.response.headers)
+ return provider_config.get_error_class(
+ error_message=error_message,
+ status_code=status_code,
+ headers=headers,
+ )
+ return e
+
+ # =========================================================
+ # CREATE INTERACTION
+ # =========================================================
+
+ def create_interaction(
+ self,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ optional_params: InteractionsAPIOptionalRequestParams,
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ model: Optional[str] = None,
+ agent: Optional[str] = None,
+ input: Optional[InteractionInput] = None,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ extra_body: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[HTTPHandler] = None,
+ _is_async: bool = False,
+ stream: Optional[bool] = None,
+ ) -> Union[
+ InteractionsAPIResponse,
+ Iterator[InteractionsAPIStreamingResponse],
+ Coroutine[Any, Any, Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]],
+ ]:
+ """
+ Create a new interaction (synchronous or async based on _is_async flag).
+
+ Per Google's OpenAPI spec, the endpoint is POST /{api_version}/interactions
+ """
+ if _is_async:
+ return self.async_create_interaction(
+ model=model,
+ agent=agent,
+ input=input,
+ interactions_api_config=interactions_api_config,
+ optional_params=optional_params,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ extra_body=extra_body,
+ timeout=timeout,
+ stream=stream,
+ )
+
+ if client is None:
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = interactions_api_config.validate_environment(
+ headers=extra_headers or {},
+ model=model or "",
+ litellm_params=litellm_params,
+ )
+
+ api_base = interactions_api_config.get_complete_url(
+ api_base=litellm_params.api_base or "",
+ model=model,
+ agent=agent,
+ litellm_params=dict(litellm_params),
+ stream=stream,
+ )
+
+ data = interactions_api_config.transform_request(
+ model=model,
+ agent=agent,
+ input=input,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ headers=headers,
+ )
+
+ if extra_body:
+ data.update(extra_body)
+
+ # Logging
+ logging_obj.pre_call(
+ input=input,
+ api_key="",
+ additional_args={
+ "complete_input_dict": data,
+ "api_base": api_base,
+ "headers": headers,
+ },
+ )
+
+ try:
+ if stream:
+ response = sync_httpx_client.post(
+ url=api_base,
+ headers=headers,
+ json=data,
+ timeout=timeout or request_timeout,
+ stream=True,
+ )
+ return self._create_sync_streaming_iterator(
+ response=response,
+ model=model,
+ logging_obj=logging_obj,
+ interactions_api_config=interactions_api_config,
+ )
+ else:
+ response = sync_httpx_client.post(
+ url=api_base,
+ headers=headers,
+ json=data,
+ timeout=timeout or request_timeout,
+ )
+ except Exception as e:
+ raise self._handle_error(e=e, provider_config=interactions_api_config)
+
+ return interactions_api_config.transform_response(
+ model=model,
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_create_interaction(
+ self,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ optional_params: InteractionsAPIOptionalRequestParams,
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ model: Optional[str] = None,
+ agent: Optional[str] = None,
+ input: Optional[InteractionInput] = None,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ extra_body: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[AsyncHTTPHandler] = None,
+ stream: Optional[bool] = None,
+ ) -> Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]:
+ """
+ Create a new interaction (async version).
+ """
+ if client is None:
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = interactions_api_config.validate_environment(
+ headers=extra_headers or {},
+ model=model or "",
+ litellm_params=litellm_params,
+ )
+
+ api_base = interactions_api_config.get_complete_url(
+ api_base=litellm_params.api_base or "",
+ model=model,
+ agent=agent,
+ litellm_params=dict(litellm_params),
+ stream=stream,
+ )
+
+ data = interactions_api_config.transform_request(
+ model=model,
+ agent=agent,
+ input=input,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ headers=headers,
+ )
+
+ if extra_body:
+ data.update(extra_body)
+
+ # Logging
+ logging_obj.pre_call(
+ input=input,
+ api_key="",
+ additional_args={
+ "complete_input_dict": data,
+ "api_base": api_base,
+ "headers": headers,
+ },
+ )
+
+ try:
+ if stream:
+ response = await async_httpx_client.post(
+ url=api_base,
+ headers=headers,
+ json=data,
+ timeout=timeout or request_timeout,
+ stream=True,
+ )
+ return self._create_async_streaming_iterator(
+ response=response,
+ model=model,
+ logging_obj=logging_obj,
+ interactions_api_config=interactions_api_config,
+ )
+ else:
+ response = await async_httpx_client.post(
+ url=api_base,
+ headers=headers,
+ json=data,
+ timeout=timeout or request_timeout,
+ )
+ except Exception as e:
+ raise self._handle_error(e=e, provider_config=interactions_api_config)
+
+ return interactions_api_config.transform_response(
+ model=model,
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def _create_sync_streaming_iterator(
+ self,
+ response: httpx.Response,
+ model: Optional[str],
+ logging_obj: LiteLLMLoggingObj,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ ) -> Iterator[InteractionsAPIStreamingResponse]:
+ """Create a synchronous streaming iterator.
+
+ Google AI's streaming format uses SSE (Server-Sent Events).
+ """
+ # Read the full response and parse as JSON array
+ full_content = response.read().decode("utf-8")
+ try:
+ chunks = json.loads(full_content)
+ if isinstance(chunks, list):
+ for parsed_chunk in chunks:
+ yield interactions_api_config.transform_streaming_response(
+ model=model,
+ parsed_chunk=parsed_chunk,
+ logging_obj=logging_obj,
+ )
+ else:
+ # Single object response
+ yield interactions_api_config.transform_streaming_response(
+ model=model,
+ parsed_chunk=chunks,
+ logging_obj=logging_obj,
+ )
+ except json.JSONDecodeError as e:
+ verbose_logger.debug(f"Failed to parse streaming response: {full_content[:500]}..., error: {e}")
+
+ async def _create_async_streaming_iterator(
+ self,
+ response: httpx.Response,
+ model: Optional[str],
+ logging_obj: LiteLLMLoggingObj,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ ) -> AsyncIterator[InteractionsAPIStreamingResponse]:
+ """Create an asynchronous streaming iterator.
+
+ Google AI's streaming format uses SSE (Server-Sent Events).
+ """
+ # Read the full response and parse as JSON array
+ full_content = (await response.aread()).decode("utf-8")
+ try:
+ chunks = json.loads(full_content)
+ if isinstance(chunks, list):
+ for parsed_chunk in chunks:
+ yield interactions_api_config.transform_streaming_response(
+ model=model,
+ parsed_chunk=parsed_chunk,
+ logging_obj=logging_obj,
+ )
+ else:
+ # Single object response
+ yield interactions_api_config.transform_streaming_response(
+ model=model,
+ parsed_chunk=chunks,
+ logging_obj=logging_obj,
+ )
+ except json.JSONDecodeError as e:
+ verbose_logger.debug(f"Failed to parse async streaming response: {full_content[:500]}..., error: {e}")
+
+ # =========================================================
+ # GET INTERACTION
+ # =========================================================
+
+ def get_interaction(
+ self,
+ interaction_id: str,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[HTTPHandler] = None,
+ _is_async: bool = False,
+ ) -> Union[InteractionsAPIResponse, Coroutine[Any, Any, InteractionsAPIResponse]]:
+ """Get an interaction by ID."""
+ if _is_async:
+ return self.async_get_interaction(
+ interaction_id=interaction_id,
+ interactions_api_config=interactions_api_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ )
+
+ if client is None:
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = interactions_api_config.validate_environment(
+ headers=extra_headers or {},
+ model="",
+ litellm_params=litellm_params,
+ )
+
+ url, params = interactions_api_config.transform_get_interaction_request(
+ interaction_id=interaction_id,
+ api_base=litellm_params.api_base or "",
+ litellm_params=litellm_params,
+ headers=headers,
+ )
+
+ logging_obj.pre_call(
+ input=interaction_id,
+ api_key="",
+ additional_args={"api_base": url, "headers": headers},
+ )
+
+ try:
+ response = sync_httpx_client.get(
+ url=url,
+ headers=headers,
+ params=params,
+ )
+ except Exception as e:
+ raise self._handle_error(e=e, provider_config=interactions_api_config)
+
+ return interactions_api_config.transform_get_interaction_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_get_interaction(
+ self,
+ interaction_id: str,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[AsyncHTTPHandler] = None,
+ ) -> InteractionsAPIResponse:
+ """Get an interaction by ID (async version)."""
+ if client is None:
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = interactions_api_config.validate_environment(
+ headers=extra_headers or {},
+ model="",
+ litellm_params=litellm_params,
+ )
+
+ url, params = interactions_api_config.transform_get_interaction_request(
+ interaction_id=interaction_id,
+ api_base=litellm_params.api_base or "",
+ litellm_params=litellm_params,
+ headers=headers,
+ )
+
+ logging_obj.pre_call(
+ input=interaction_id,
+ api_key="",
+ additional_args={"api_base": url, "headers": headers},
+ )
+
+ try:
+ response = await async_httpx_client.get(
+ url=url,
+ headers=headers,
+ params=params,
+ )
+ except Exception as e:
+ raise self._handle_error(e=e, provider_config=interactions_api_config)
+
+ return interactions_api_config.transform_get_interaction_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ # =========================================================
+ # DELETE INTERACTION
+ # =========================================================
+
+ def delete_interaction(
+ self,
+ interaction_id: str,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[HTTPHandler] = None,
+ _is_async: bool = False,
+ ) -> Union[DeleteInteractionResult, Coroutine[Any, Any, DeleteInteractionResult]]:
+ """Delete an interaction by ID."""
+ if _is_async:
+ return self.async_delete_interaction(
+ interaction_id=interaction_id,
+ interactions_api_config=interactions_api_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ )
+
+ if client is None:
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = interactions_api_config.validate_environment(
+ headers=extra_headers or {},
+ model="",
+ litellm_params=litellm_params,
+ )
+
+ url, data = interactions_api_config.transform_delete_interaction_request(
+ interaction_id=interaction_id,
+ api_base=litellm_params.api_base or "",
+ litellm_params=litellm_params,
+ headers=headers,
+ )
+
+ logging_obj.pre_call(
+ input=interaction_id,
+ api_key="",
+ additional_args={"api_base": url, "headers": headers},
+ )
+
+ try:
+ response = sync_httpx_client.delete(
+ url=url,
+ headers=headers,
+ timeout=timeout or request_timeout,
+ )
+ except Exception as e:
+ raise self._handle_error(e=e, provider_config=interactions_api_config)
+
+ return interactions_api_config.transform_delete_interaction_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ interaction_id=interaction_id,
+ )
+
+ async def async_delete_interaction(
+ self,
+ interaction_id: str,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[AsyncHTTPHandler] = None,
+ ) -> DeleteInteractionResult:
+ """Delete an interaction by ID (async version)."""
+ if client is None:
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = interactions_api_config.validate_environment(
+ headers=extra_headers or {},
+ model="",
+ litellm_params=litellm_params,
+ )
+
+ url, data = interactions_api_config.transform_delete_interaction_request(
+ interaction_id=interaction_id,
+ api_base=litellm_params.api_base or "",
+ litellm_params=litellm_params,
+ headers=headers,
+ )
+
+ logging_obj.pre_call(
+ input=interaction_id,
+ api_key="",
+ additional_args={"api_base": url, "headers": headers},
+ )
+
+ try:
+ response = await async_httpx_client.delete(
+ url=url,
+ headers=headers,
+ timeout=timeout or request_timeout,
+ )
+ except Exception as e:
+ raise self._handle_error(e=e, provider_config=interactions_api_config)
+
+ return interactions_api_config.transform_delete_interaction_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ interaction_id=interaction_id,
+ )
+
+ # =========================================================
+ # CANCEL INTERACTION
+ # =========================================================
+
+ def cancel_interaction(
+ self,
+ interaction_id: str,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[HTTPHandler] = None,
+ _is_async: bool = False,
+ ) -> Union[CancelInteractionResult, Coroutine[Any, Any, CancelInteractionResult]]:
+ """Cancel an interaction by ID."""
+ if _is_async:
+ return self.async_cancel_interaction(
+ interaction_id=interaction_id,
+ interactions_api_config=interactions_api_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ )
+
+ if client is None:
+ sync_httpx_client = _get_httpx_client(
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ )
+ else:
+ sync_httpx_client = client
+
+ headers = interactions_api_config.validate_environment(
+ headers=extra_headers or {},
+ model="",
+ litellm_params=litellm_params,
+ )
+
+ url, data = interactions_api_config.transform_cancel_interaction_request(
+ interaction_id=interaction_id,
+ api_base=litellm_params.api_base or "",
+ litellm_params=litellm_params,
+ headers=headers,
+ )
+
+ logging_obj.pre_call(
+ input=interaction_id,
+ api_key="",
+ additional_args={"api_base": url, "headers": headers},
+ )
+
+ try:
+ response = sync_httpx_client.post(
+ url=url,
+ headers=headers,
+ json=data,
+ timeout=timeout or request_timeout,
+ )
+ except Exception as e:
+ raise self._handle_error(e=e, provider_config=interactions_api_config)
+
+ return interactions_api_config.transform_cancel_interaction_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ async def async_cancel_interaction(
+ self,
+ interaction_id: str,
+ interactions_api_config: BaseInteractionsAPIConfig,
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ client: Optional[AsyncHTTPHandler] = None,
+ ) -> CancelInteractionResult:
+ """Cancel an interaction by ID (async version)."""
+ if client is None:
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders(custom_llm_provider),
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ )
+ else:
+ async_httpx_client = client
+
+ headers = interactions_api_config.validate_environment(
+ headers=extra_headers or {},
+ model="",
+ litellm_params=litellm_params,
+ )
+
+ url, data = interactions_api_config.transform_cancel_interaction_request(
+ interaction_id=interaction_id,
+ api_base=litellm_params.api_base or "",
+ litellm_params=litellm_params,
+ headers=headers,
+ )
+
+ logging_obj.pre_call(
+ input=interaction_id,
+ api_key="",
+ additional_args={"api_base": url, "headers": headers},
+ )
+
+ try:
+ response = await async_httpx_client.post(
+ url=url,
+ headers=headers,
+ json=data,
+ timeout=timeout or request_timeout,
+ )
+ except Exception as e:
+ raise self._handle_error(e=e, provider_config=interactions_api_config)
+
+ return interactions_api_config.transform_cancel_interaction_response(
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+
+# Initialize the HTTP handler singleton
+interactions_http_handler = InteractionsHTTPHandler()
+
diff --git a/litellm/interactions/main.py b/litellm/interactions/main.py
new file mode 100644
index 00000000000..9fb58fc73d6
--- /dev/null
+++ b/litellm/interactions/main.py
@@ -0,0 +1,621 @@
+"""
+LiteLLM Interactions API - Main Module
+
+Per OpenAPI spec (https://ai.google.dev/static/api/interactions.openapi.json):
+- Create interaction: POST /{api_version}/interactions
+- Get interaction: GET /{api_version}/interactions/{interaction_id}
+- Delete interaction: DELETE /{api_version}/interactions/{interaction_id}
+
+Usage:
+ import litellm
+
+ # Create an interaction with a model
+ response = litellm.interactions.create(
+ model="gemini-2.5-flash",
+ input="Hello, how are you?"
+ )
+
+ # Create an interaction with an agent
+ response = litellm.interactions.create(
+ agent="deep-research-pro-preview-12-2025",
+ input="Research the current state of cancer research"
+ )
+
+ # Async version
+ response = await litellm.interactions.acreate(...)
+
+ # Get an interaction
+ response = litellm.interactions.get(interaction_id="...")
+
+ # Delete an interaction
+ result = litellm.interactions.delete(interaction_id="...")
+"""
+
+import asyncio
+import contextvars
+from functools import partial
+from typing import (
+ Any,
+ AsyncIterator,
+ Coroutine,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Union,
+)
+
+import httpx
+
+import litellm
+from litellm.interactions.http_handler import interactions_http_handler
+from litellm.interactions.utils import (
+ InteractionsAPIRequestUtils,
+ get_provider_interactions_api_config,
+)
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.types.interactions import (
+ CancelInteractionResult,
+ DeleteInteractionResult,
+ InteractionInput,
+ InteractionsAPIResponse,
+ InteractionsAPIStreamingResponse,
+ InteractionTool,
+)
+from litellm.types.router import GenericLiteLLMParams
+from litellm.utils import client
+
+# ============================================================
+# SDK Methods - CREATE INTERACTION
+# ============================================================
+
+
+@client
+async def acreate(
+ # Model or Agent (one required per OpenAPI spec)
+ model: Optional[str] = None,
+ agent: Optional[str] = None,
+ # Input (required)
+ input: Optional[InteractionInput] = None,
+ # Tools (for model interactions)
+ tools: Optional[List[InteractionTool]] = None,
+ # System instruction
+ system_instruction: Optional[str] = None,
+ # Generation config
+ generation_config: Optional[Dict[str, Any]] = None,
+ # Streaming
+ stream: Optional[bool] = None,
+ # Storage
+ store: Optional[bool] = None,
+ # Background execution
+ background: Optional[bool] = None,
+ # Response format
+ response_modalities: Optional[List[str]] = None,
+ response_format: Optional[Dict[str, Any]] = None,
+ response_mime_type: Optional[str] = None,
+ # Continuation
+ previous_interaction_id: Optional[str] = None,
+ # Extra params
+ extra_headers: Optional[Dict[str, Any]] = None,
+ extra_body: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ # LiteLLM params
+ custom_llm_provider: Optional[str] = None,
+ **kwargs,
+) -> Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]:
+ """
+ Async: Create a new interaction using Google's Interactions API.
+
+ Per OpenAPI spec, provide either `model` or `agent`.
+
+ Args:
+ model: The model to use (e.g., "gemini-2.5-flash")
+ agent: The agent to use (e.g., "deep-research-pro-preview-12-2025")
+ input: The input content (string, content object, or list)
+ tools: Tools available for the model
+ system_instruction: System instruction for the interaction
+ generation_config: Generation configuration
+ stream: Whether to stream the response
+ store: Whether to store the response for later retrieval
+ background: Whether to run in background
+ response_modalities: Requested response modalities (TEXT, IMAGE, AUDIO)
+ response_format: JSON schema for response format
+ response_mime_type: MIME type of the response
+ previous_interaction_id: ID of previous interaction for continuation
+ extra_headers: Additional headers
+ extra_body: Additional body parameters
+ timeout: Request timeout
+ custom_llm_provider: Override the LLM provider
+
+ Returns:
+ InteractionsAPIResponse or async iterator for streaming
+ """
+ local_vars = locals()
+ try:
+ loop = asyncio.get_event_loop()
+ kwargs["acreate_interaction"] = True
+
+ if custom_llm_provider is None and model:
+ _, custom_llm_provider, _, _ = litellm.get_llm_provider(
+ model=model, api_base=kwargs.get("api_base", None)
+ )
+ elif custom_llm_provider is None:
+ custom_llm_provider = "gemini"
+
+ func = partial(
+ create,
+ model=model,
+ agent=agent,
+ input=input,
+ tools=tools,
+ system_instruction=system_instruction,
+ generation_config=generation_config,
+ stream=stream,
+ store=store,
+ background=background,
+ response_modalities=response_modalities,
+ response_format=response_format,
+ response_mime_type=response_mime_type,
+ previous_interaction_id=previous_interaction_id,
+ extra_headers=extra_headers,
+ extra_body=extra_body,
+ timeout=timeout,
+ custom_llm_provider=custom_llm_provider,
+ **kwargs,
+ )
+
+ ctx = contextvars.copy_context()
+ func_with_context = partial(ctx.run, func)
+ init_response = await loop.run_in_executor(None, func_with_context)
+
+ if asyncio.iscoroutine(init_response):
+ response = await init_response
+ else:
+ response = init_response
+
+ return response # type: ignore
+ except Exception as e:
+ raise litellm.exception_type(
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
+
+
+@client
+def create(
+ # Model or Agent (one required per OpenAPI spec)
+ model: Optional[str] = None,
+ agent: Optional[str] = None,
+ # Input (required)
+ input: Optional[InteractionInput] = None,
+ # Tools (for model interactions)
+ tools: Optional[List[InteractionTool]] = None,
+ # System instruction
+ system_instruction: Optional[str] = None,
+ # Generation config
+ generation_config: Optional[Dict[str, Any]] = None,
+ # Streaming
+ stream: Optional[bool] = None,
+ # Storage
+ store: Optional[bool] = None,
+ # Background execution
+ background: Optional[bool] = None,
+ # Response format
+ response_modalities: Optional[List[str]] = None,
+ response_format: Optional[Dict[str, Any]] = None,
+ response_mime_type: Optional[str] = None,
+ # Continuation
+ previous_interaction_id: Optional[str] = None,
+ # Extra params
+ extra_headers: Optional[Dict[str, Any]] = None,
+ extra_body: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ # LiteLLM params
+ custom_llm_provider: Optional[str] = None,
+ **kwargs,
+) -> Union[
+ InteractionsAPIResponse,
+ Iterator[InteractionsAPIStreamingResponse],
+ Coroutine[Any, Any, Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]],
+]:
+ """
+ Sync: Create a new interaction using Google's Interactions API.
+
+ Per OpenAPI spec, provide either `model` or `agent`.
+
+ Args:
+ model: The model to use (e.g., "gemini-2.5-flash")
+ agent: The agent to use (e.g., "deep-research-pro-preview-12-2025")
+ input: The input content (string, content object, or list)
+ tools: Tools available for the model
+ system_instruction: System instruction for the interaction
+ generation_config: Generation configuration
+ stream: Whether to stream the response
+ store: Whether to store the response for later retrieval
+ background: Whether to run in background
+ response_modalities: Requested response modalities (TEXT, IMAGE, AUDIO)
+ response_format: JSON schema for response format
+ response_mime_type: MIME type of the response
+ previous_interaction_id: ID of previous interaction for continuation
+ extra_headers: Additional headers
+ extra_body: Additional body parameters
+ timeout: Request timeout
+ custom_llm_provider: Override the LLM provider
+
+ Returns:
+ InteractionsAPIResponse or iterator for streaming
+ """
+ local_vars = locals()
+
+ try:
+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore
+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)
+ _is_async = kwargs.pop("acreate_interaction", False) is True
+
+ litellm_params = GenericLiteLLMParams(**kwargs)
+
+ if model:
+ model, custom_llm_provider, _, _ = litellm.get_llm_provider(
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ api_base=litellm_params.api_base,
+ api_key=litellm_params.api_key,
+ )
+ else:
+ custom_llm_provider = custom_llm_provider or "gemini"
+
+ interactions_api_config = get_provider_interactions_api_config(
+ provider=custom_llm_provider,
+ model=model,
+ )
+
+ if interactions_api_config is None:
+ raise ValueError(
+ f"Interactions API is not supported for provider: {custom_llm_provider}. "
+ "Currently only 'gemini' is supported."
+ )
+
+ # Get optional params using utility (similar to responses API pattern)
+ local_vars.update(kwargs)
+ optional_params = InteractionsAPIRequestUtils.get_requested_interactions_api_optional_params(
+ local_vars
+ )
+
+ litellm_logging_obj.update_environment_variables(
+ model=model,
+ optional_params=dict(optional_params),
+ litellm_params={"litellm_call_id": litellm_call_id},
+ custom_llm_provider=custom_llm_provider,
+ )
+
+ response = interactions_http_handler.create_interaction(
+ model=model,
+ agent=agent,
+ input=input,
+ interactions_api_config=interactions_api_config,
+ optional_params=optional_params,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=litellm_logging_obj,
+ extra_headers=extra_headers,
+ extra_body=extra_body,
+ timeout=timeout,
+ _is_async=_is_async,
+ stream=stream,
+ )
+
+ return response
+ except Exception as e:
+ raise litellm.exception_type(
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
+
+
+# ============================================================
+# SDK Methods - GET INTERACTION
+# ============================================================
+
+
+@client
+async def aget(
+ interaction_id: str,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ custom_llm_provider: Optional[str] = None,
+ **kwargs,
+) -> InteractionsAPIResponse:
+ """Async: Get an interaction by its ID."""
+ local_vars = locals()
+ try:
+ loop = asyncio.get_event_loop()
+ kwargs["aget_interaction"] = True
+
+ func = partial(
+ get,
+ interaction_id=interaction_id,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ custom_llm_provider=custom_llm_provider or "gemini",
+ **kwargs,
+ )
+
+ ctx = contextvars.copy_context()
+ func_with_context = partial(ctx.run, func)
+ init_response = await loop.run_in_executor(None, func_with_context)
+
+ if asyncio.iscoroutine(init_response):
+ response = await init_response
+ else:
+ response = init_response
+
+ return response # type: ignore
+ except Exception as e:
+ raise litellm.exception_type(
+ model=None,
+ custom_llm_provider=custom_llm_provider or "gemini",
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
+
+
+@client
+def get(
+ interaction_id: str,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ custom_llm_provider: Optional[str] = None,
+ **kwargs,
+) -> Union[InteractionsAPIResponse, Coroutine[Any, Any, InteractionsAPIResponse]]:
+ """Sync: Get an interaction by its ID."""
+ local_vars = locals()
+ custom_llm_provider = custom_llm_provider or "gemini"
+
+ try:
+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore
+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)
+ _is_async = kwargs.pop("aget_interaction", False) is True
+
+ litellm_params = GenericLiteLLMParams(**kwargs)
+
+ interactions_api_config = get_provider_interactions_api_config(
+ provider=custom_llm_provider,
+ )
+
+ if interactions_api_config is None:
+ raise ValueError(f"Interactions API not supported for: {custom_llm_provider}")
+
+ litellm_logging_obj.update_environment_variables(
+ model=None,
+ optional_params={"interaction_id": interaction_id},
+ litellm_params={"litellm_call_id": litellm_call_id},
+ custom_llm_provider=custom_llm_provider,
+ )
+
+ return interactions_http_handler.get_interaction(
+ interaction_id=interaction_id,
+ interactions_api_config=interactions_api_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=litellm_logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ _is_async=_is_async,
+ )
+ except Exception as e:
+ raise litellm.exception_type(
+ model=None,
+ custom_llm_provider=custom_llm_provider,
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
+
+
+# ============================================================
+# SDK Methods - DELETE INTERACTION
+# ============================================================
+
+
+@client
+async def adelete(
+ interaction_id: str,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ custom_llm_provider: Optional[str] = None,
+ **kwargs,
+) -> DeleteInteractionResult:
+ """Async: Delete an interaction by its ID."""
+ local_vars = locals()
+ try:
+ loop = asyncio.get_event_loop()
+ kwargs["adelete_interaction"] = True
+
+ func = partial(
+ delete,
+ interaction_id=interaction_id,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ custom_llm_provider=custom_llm_provider or "gemini",
+ **kwargs,
+ )
+
+ ctx = contextvars.copy_context()
+ func_with_context = partial(ctx.run, func)
+ init_response = await loop.run_in_executor(None, func_with_context)
+
+ if asyncio.iscoroutine(init_response):
+ response = await init_response
+ else:
+ response = init_response
+
+ return response # type: ignore
+ except Exception as e:
+ raise litellm.exception_type(
+ model=None,
+ custom_llm_provider=custom_llm_provider or "gemini",
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
+
+
+@client
+def delete(
+ interaction_id: str,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ custom_llm_provider: Optional[str] = None,
+ **kwargs,
+) -> Union[DeleteInteractionResult, Coroutine[Any, Any, DeleteInteractionResult]]:
+ """Sync: Delete an interaction by its ID."""
+ local_vars = locals()
+ custom_llm_provider = custom_llm_provider or "gemini"
+
+ try:
+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore
+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)
+ _is_async = kwargs.pop("adelete_interaction", False) is True
+
+ litellm_params = GenericLiteLLMParams(**kwargs)
+
+ interactions_api_config = get_provider_interactions_api_config(
+ provider=custom_llm_provider,
+ )
+
+ if interactions_api_config is None:
+ raise ValueError(f"Interactions API not supported for: {custom_llm_provider}")
+
+ litellm_logging_obj.update_environment_variables(
+ model=None,
+ optional_params={"interaction_id": interaction_id},
+ litellm_params={"litellm_call_id": litellm_call_id},
+ custom_llm_provider=custom_llm_provider,
+ )
+
+ return interactions_http_handler.delete_interaction(
+ interaction_id=interaction_id,
+ interactions_api_config=interactions_api_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=litellm_logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ _is_async=_is_async,
+ )
+ except Exception as e:
+ raise litellm.exception_type(
+ model=None,
+ custom_llm_provider=custom_llm_provider,
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
+
+
+# ============================================================
+# SDK Methods - CANCEL INTERACTION
+# ============================================================
+
+
+@client
+async def acancel(
+ interaction_id: str,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ custom_llm_provider: Optional[str] = None,
+ **kwargs,
+) -> CancelInteractionResult:
+ """Async: Cancel an interaction by its ID."""
+ local_vars = locals()
+ try:
+ loop = asyncio.get_event_loop()
+ kwargs["acancel_interaction"] = True
+
+ func = partial(
+ cancel,
+ interaction_id=interaction_id,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ custom_llm_provider=custom_llm_provider or "gemini",
+ **kwargs,
+ )
+
+ ctx = contextvars.copy_context()
+ func_with_context = partial(ctx.run, func)
+ init_response = await loop.run_in_executor(None, func_with_context)
+
+ if asyncio.iscoroutine(init_response):
+ response = await init_response
+ else:
+ response = init_response
+
+ return response # type: ignore
+ except Exception as e:
+ raise litellm.exception_type(
+ model=None,
+ custom_llm_provider=custom_llm_provider or "gemini",
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
+
+
+@client
+def cancel(
+ interaction_id: str,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ custom_llm_provider: Optional[str] = None,
+ **kwargs,
+) -> Union[CancelInteractionResult, Coroutine[Any, Any, CancelInteractionResult]]:
+ """Sync: Cancel an interaction by its ID."""
+ local_vars = locals()
+ custom_llm_provider = custom_llm_provider or "gemini"
+
+ try:
+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore
+ litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)
+ _is_async = kwargs.pop("acancel_interaction", False) is True
+
+ litellm_params = GenericLiteLLMParams(**kwargs)
+
+ interactions_api_config = get_provider_interactions_api_config(
+ provider=custom_llm_provider,
+ )
+
+ if interactions_api_config is None:
+ raise ValueError(f"Interactions API not supported for: {custom_llm_provider}")
+
+ litellm_logging_obj.update_environment_variables(
+ model=None,
+ optional_params={"interaction_id": interaction_id},
+ litellm_params={"litellm_call_id": litellm_call_id},
+ custom_llm_provider=custom_llm_provider,
+ )
+
+ return interactions_http_handler.cancel_interaction(
+ interaction_id=interaction_id,
+ interactions_api_config=interactions_api_config,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=litellm_logging_obj,
+ extra_headers=extra_headers,
+ timeout=timeout,
+ _is_async=_is_async,
+ )
+ except Exception as e:
+ raise litellm.exception_type(
+ model=None,
+ custom_llm_provider=custom_llm_provider,
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
diff --git a/litellm/interactions/utils.py b/litellm/interactions/utils.py
new file mode 100644
index 00000000000..4fc40916e52
--- /dev/null
+++ b/litellm/interactions/utils.py
@@ -0,0 +1,84 @@
+"""
+Utility functions for Interactions API.
+"""
+
+from typing import Any, Dict, Optional, cast
+
+from litellm.llms.base_llm.interactions.transformation import BaseInteractionsAPIConfig
+from litellm.types.interactions import InteractionsAPIOptionalRequestParams
+
+# Valid optional parameter keys per OpenAPI spec
+INTERACTIONS_API_OPTIONAL_PARAMS = {
+ "tools",
+ "system_instruction",
+ "generation_config",
+ "stream",
+ "store",
+ "background",
+ "response_modalities",
+ "response_format",
+ "response_mime_type",
+ "previous_interaction_id",
+ "agent_config",
+}
+
+
+def get_provider_interactions_api_config(
+ provider: str,
+ model: Optional[str] = None,
+) -> Optional[BaseInteractionsAPIConfig]:
+ """
+ Get the interactions API config for the given provider.
+
+ Args:
+ provider: The LLM provider name
+ model: Optional model name
+
+ Returns:
+ The provider-specific interactions API config, or None if not supported
+ """
+ from litellm.types.utils import LlmProviders
+
+ if provider == LlmProviders.GEMINI.value or provider == "gemini":
+ from litellm.llms.gemini.interactions.transformation import (
+ GoogleAIStudioInteractionsConfig,
+ )
+ return GoogleAIStudioInteractionsConfig()
+
+ return None
+
+
+class InteractionsAPIRequestUtils:
+ """Helper utils for constructing Interactions API requests."""
+
+ @staticmethod
+ def get_requested_interactions_api_optional_params(
+ params: Dict[str, Any],
+ ) -> InteractionsAPIOptionalRequestParams:
+ """
+ Filter parameters to only include valid optional params per OpenAPI spec.
+
+ Args:
+ params: Dictionary of parameters to filter (typically from locals())
+
+ Returns:
+ Dict with only the valid optional parameters
+ """
+ from litellm.utils import PreProcessNonDefaultParams
+
+ custom_llm_provider = params.pop("custom_llm_provider", None)
+ special_params = params.pop("kwargs", {})
+ additional_drop_params = params.pop("additional_drop_params", None)
+
+ non_default_params = (
+ PreProcessNonDefaultParams.base_pre_process_non_default_params(
+ passed_params=params,
+ special_params=special_params,
+ custom_llm_provider=custom_llm_provider,
+ additional_drop_params=additional_drop_params,
+ default_param_values={k: None for k in INTERACTIONS_API_OPTIONAL_PARAMS},
+ additional_endpoint_specific_params=["input", "model", "agent"],
+ )
+ )
+
+ return cast(InteractionsAPIOptionalRequestParams, non_default_params)
diff --git a/litellm/llms/base_llm/interactions/__init__.py b/litellm/llms/base_llm/interactions/__init__.py
new file mode 100644
index 00000000000..2bec120f597
--- /dev/null
+++ b/litellm/llms/base_llm/interactions/__init__.py
@@ -0,0 +1,5 @@
+"""Base classes for Interactions API implementations."""
+
+from litellm.llms.base_llm.interactions.transformation import BaseInteractionsAPIConfig
+
+__all__ = ["BaseInteractionsAPIConfig"]
diff --git a/litellm/llms/base_llm/interactions/transformation.py b/litellm/llms/base_llm/interactions/transformation.py
new file mode 100644
index 00000000000..4ceb3f5387b
--- /dev/null
+++ b/litellm/llms/base_llm/interactions/transformation.py
@@ -0,0 +1,313 @@
+"""
+Base transformation class for Interactions API implementations.
+
+This follows the same pattern as BaseResponsesAPIConfig for the Responses API.
+
+Per OpenAPI spec (https://ai.google.dev/static/api/interactions.openapi.json):
+- Create: POST /{api_version}/interactions
+- Get: GET /{api_version}/interactions/{interaction_id}
+- Delete: DELETE /{api_version}/interactions/{interaction_id}
+"""
+
+import types
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
+
+import httpx
+
+from litellm.types.interactions import (
+ CancelInteractionResult,
+ DeleteInteractionResult,
+ InteractionInput,
+ InteractionsAPIOptionalRequestParams,
+ InteractionsAPIResponse,
+ InteractionsAPIStreamingResponse,
+)
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import LlmProviders
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
+
+ from ..chat.transformation import BaseLLMException as _BaseLLMException
+
+ LiteLLMLoggingObj = _LiteLLMLoggingObj
+ BaseLLMException = _BaseLLMException
+else:
+ LiteLLMLoggingObj = Any
+ BaseLLMException = Any
+
+
+class BaseInteractionsAPIConfig(ABC):
+ """
+ Base configuration class for Google Interactions API implementations.
+
+ Per OpenAPI spec, the Interactions API supports two types of interactions:
+ - Model interactions (with model parameter)
+ - Agent interactions (with agent parameter)
+
+ Implementations should override the abstract methods to provide
+ provider-specific transformations for requests and responses.
+ """
+
+ def __init__(self):
+ pass
+
+ @property
+ @abstractmethod
+ def custom_llm_provider(self) -> LlmProviders:
+ """Return the LLM provider identifier."""
+ pass
+
+ @classmethod
+ def get_config(cls):
+ return {
+ k: v
+ for k, v in cls.__dict__.items()
+ if not k.startswith("__")
+ and not k.startswith("_abc")
+ and not isinstance(
+ v,
+ (
+ types.FunctionType,
+ types.BuiltinFunctionType,
+ classmethod,
+ staticmethod,
+ ),
+ )
+ and v is not None
+ }
+
+ @abstractmethod
+ def get_supported_params(self, model: str) -> List[str]:
+ """
+ Return the list of supported parameters for the given model.
+ """
+ pass
+
+ @abstractmethod
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ litellm_params: Optional[GenericLiteLLMParams]
+ ) -> dict:
+ """
+ Validate and prepare environment settings including headers.
+ """
+ return {}
+
+ @abstractmethod
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ model: Optional[str],
+ agent: Optional[str] = None,
+ litellm_params: Optional[dict] = None,
+ stream: Optional[bool] = None,
+ ) -> str:
+ """
+ Get the complete URL for the interaction request.
+
+ Per OpenAPI spec: POST /{api_version}/interactions
+
+ Args:
+ api_base: Base URL for the API
+ model: The model name (for model interactions)
+ agent: The agent name (for agent interactions)
+ litellm_params: LiteLLM parameters
+ stream: Whether this is a streaming request
+
+ Returns:
+ The complete URL for the request
+ """
+ if api_base is None:
+ raise ValueError("api_base is required")
+ return api_base
+
+ @abstractmethod
+ def transform_request(
+ self,
+ model: Optional[str],
+ agent: Optional[str],
+ input: Optional[InteractionInput],
+ optional_params: InteractionsAPIOptionalRequestParams,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Dict:
+ """
+ Transform the input request into the provider's expected format.
+
+ Per OpenAPI spec, the request body should be either:
+ - CreateModelInteractionParams (with model)
+ - CreateAgentInteractionParams (with agent)
+
+ Args:
+ model: The model name (for model interactions)
+ agent: The agent name (for agent interactions)
+ input: The input content (string, content object, or list)
+ optional_params: Optional parameters for the request
+ litellm_params: LiteLLM-specific parameters
+ headers: Request headers
+
+ Returns:
+ The transformed request body as a dictionary
+ """
+ pass
+
+ @abstractmethod
+ def transform_response(
+ self,
+ model: Optional[str],
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> InteractionsAPIResponse:
+ """
+ Transform the raw HTTP response into an InteractionsAPIResponse.
+
+ Per OpenAPI spec, the response is an Interaction object.
+ """
+ pass
+
+ @abstractmethod
+ def transform_streaming_response(
+ self,
+ model: Optional[str],
+ parsed_chunk: dict,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> InteractionsAPIStreamingResponse:
+ """
+ Transform a parsed streaming response chunk into an InteractionsAPIStreamingResponse.
+
+ Per OpenAPI spec, streaming uses SSE with various event types.
+ """
+ pass
+
+ # =========================================================
+ # GET INTERACTION TRANSFORMATION
+ # =========================================================
+
+ @abstractmethod
+ def transform_get_interaction_request(
+ self,
+ interaction_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Transform the get interaction request into URL and query params.
+
+ Per OpenAPI spec: GET /{api_version}/interactions/{interaction_id}
+
+ Returns:
+ Tuple of (URL, query_params)
+ """
+ pass
+
+ @abstractmethod
+ def transform_get_interaction_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> InteractionsAPIResponse:
+ """
+ Transform the get interaction response.
+ """
+ pass
+
+ # =========================================================
+ # DELETE INTERACTION TRANSFORMATION
+ # =========================================================
+
+ @abstractmethod
+ def transform_delete_interaction_request(
+ self,
+ interaction_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Transform the delete interaction request into URL and body.
+
+ Per OpenAPI spec: DELETE /{api_version}/interactions/{interaction_id}
+
+ Returns:
+ Tuple of (URL, request_body)
+ """
+ pass
+
+ @abstractmethod
+ def transform_delete_interaction_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ interaction_id: str,
+ ) -> DeleteInteractionResult:
+ """
+ Transform the delete interaction response.
+ """
+ pass
+
+ # =========================================================
+ # CANCEL INTERACTION TRANSFORMATION
+ # =========================================================
+
+ @abstractmethod
+ def transform_cancel_interaction_request(
+ self,
+ interaction_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """
+ Transform the cancel interaction request into URL and body.
+
+ Returns:
+ Tuple of (URL, request_body)
+ """
+ pass
+
+ @abstractmethod
+ def transform_cancel_interaction_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> CancelInteractionResult:
+ """
+ Transform the cancel interaction response.
+ """
+ pass
+
+ # =========================================================
+ # ERROR HANDLING
+ # =========================================================
+
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]
+ ) -> BaseLLMException:
+ """
+ Get the appropriate exception class for an error.
+ """
+ from ..chat.transformation import BaseLLMException
+
+ raise BaseLLMException(
+ status_code=status_code,
+ message=error_message,
+ headers=headers,
+ )
+
+ def should_fake_stream(
+ self,
+ model: Optional[str],
+ stream: Optional[bool],
+ custom_llm_provider: Optional[str] = None,
+ ) -> bool:
+ """
+ Returns True if litellm should fake a stream for the given model.
+
+ Override in subclasses if the provider doesn't support native streaming.
+ """
+ return False
diff --git a/litellm/llms/gemini/interactions/__init__.py b/litellm/llms/gemini/interactions/__init__.py
new file mode 100644
index 00000000000..1752d489a0c
--- /dev/null
+++ b/litellm/llms/gemini/interactions/__init__.py
@@ -0,0 +1,7 @@
+"""Google AI Studio Interactions API implementation."""
+
+from litellm.llms.gemini.interactions.transformation import (
+ GoogleAIStudioInteractionsConfig,
+)
+
+__all__ = ["GoogleAIStudioInteractionsConfig"]
diff --git a/litellm/llms/gemini/interactions/transformation.py b/litellm/llms/gemini/interactions/transformation.py
new file mode 100644
index 00000000000..d9ff468fd71
--- /dev/null
+++ b/litellm/llms/gemini/interactions/transformation.py
@@ -0,0 +1,262 @@
+"""
+Google AI Studio Interactions API configuration.
+
+Per OpenAPI spec (https://ai.google.dev/static/api/interactions.openapi.json):
+- Create: POST https://generativelanguage.googleapis.com/{api_version}/interactions
+- Get: GET https://generativelanguage.googleapis.com/{api_version}/interactions/{interaction_id}
+- Delete: DELETE https://generativelanguage.googleapis.com/{api_version}/interactions/{interaction_id}
+
+This is a thin wrapper - no transformation needed since we follow the spec directly.
+"""
+
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
+
+import httpx
+
+from litellm._logging import verbose_logger
+from litellm.litellm_core_utils.core_helpers import process_response_headers
+from litellm.llms.base_llm.interactions.transformation import BaseInteractionsAPIConfig
+from litellm.llms.gemini.common_utils import GeminiError, GeminiModelInfo
+from litellm.types.interactions import (
+ CancelInteractionResult,
+ DeleteInteractionResult,
+ InteractionInput,
+ InteractionsAPIOptionalRequestParams,
+ InteractionsAPIResponse,
+ InteractionsAPIStreamingResponse,
+)
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import LlmProviders
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
+
+ LiteLLMLoggingObj = _LiteLLMLoggingObj
+else:
+ LiteLLMLoggingObj = Any
+
+
+class GoogleAIStudioInteractionsConfig(BaseInteractionsAPIConfig):
+ """
+ Configuration for Google AI Studio Interactions API.
+
+ Minimal config - we follow the OpenAPI spec directly with no transformation.
+ """
+
+ @property
+ def custom_llm_provider(self) -> LlmProviders:
+ return LlmProviders.GEMINI
+
+ @property
+ def api_version(self) -> str:
+ return "v1beta"
+
+ def get_supported_params(self, model: str) -> List[str]:
+ """Per OpenAPI spec CreateModelInteractionParams."""
+ return [
+ "model", "agent", "input", "tools", "system_instruction",
+ "generation_config", "stream", "store", "background",
+ "response_modalities", "response_format", "response_mime_type",
+ "previous_interaction_id",
+ ]
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ litellm_params: Optional[GenericLiteLLMParams],
+ ) -> dict:
+ """Google AI Studio uses API key in query params, not headers."""
+ headers = headers or {}
+ headers["Content-Type"] = "application/json"
+ return headers
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ model: Optional[str],
+ agent: Optional[str] = None,
+ litellm_params: Optional[dict] = None,
+ stream: Optional[bool] = None,
+ ) -> str:
+ """POST /{api_version}/interactions"""
+ litellm_params = litellm_params or {}
+ api_base = GeminiModelInfo.get_api_base(api_base)
+ api_key = GeminiModelInfo.get_api_key(litellm_params.get("api_key"))
+
+ if not api_key:
+ raise ValueError(
+ "Google API key is required. Set GOOGLE_API_KEY or GEMINI_API_KEY environment variable."
+ )
+
+ query_params = f"key={api_key}"
+ if stream:
+ query_params += "&alt=sse"
+
+ return f"{api_base}/{self.api_version}/interactions?{query_params}"
+
+ def transform_request(
+ self,
+ model: Optional[str],
+ agent: Optional[str],
+ input: Optional[InteractionInput],
+ optional_params: InteractionsAPIOptionalRequestParams,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Dict:
+ """
+ Build request body per OpenAPI spec - minimal transformation.
+ """
+ request_body: Dict[str, Any] = {}
+
+ # Model or Agent (one required)
+ if model:
+ request_body["model"] = GeminiModelInfo.get_base_model(model) or model
+ elif agent:
+ request_body["agent"] = agent
+ else:
+ raise ValueError("Either 'model' or 'agent' must be provided")
+
+ # Input
+ if input is not None:
+ request_body["input"] = input
+
+ # Pass through optional params directly (they match the spec)
+ optional_keys = [
+ "tools", "system_instruction", "generation_config", "store",
+ "background", "response_modalities", "response_format",
+ "response_mime_type", "previous_interaction_id",
+ ]
+ for key in optional_keys:
+ if optional_params.get(key) is not None:
+ request_body[key] = optional_params[key]
+
+ return request_body
+
+ def transform_response(
+ self,
+ model: Optional[str],
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> InteractionsAPIResponse:
+ """Parse response - it already matches our response type."""
+ try:
+ logging_obj.post_call(
+ original_response=raw_response.text,
+ additional_args={"complete_input_dict": {}},
+ )
+ raw_json = raw_response.json()
+ except Exception:
+ raise GeminiError(
+ message=raw_response.text,
+ status_code=raw_response.status_code,
+ headers=dict(raw_response.headers),
+ )
+
+ verbose_logger.debug("Google AI Interactions response: %s", raw_json)
+
+ response = InteractionsAPIResponse(**raw_json)
+ response._hidden_params["headers"] = dict(raw_response.headers)
+ response._hidden_params["additional_headers"] = process_response_headers(dict(raw_response.headers))
+
+ return response
+
+ def transform_streaming_response(
+ self,
+ model: Optional[str],
+ parsed_chunk: dict,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> InteractionsAPIStreamingResponse:
+ """Parse streaming chunk."""
+ verbose_logger.debug("Google AI Interactions streaming chunk: %s", parsed_chunk)
+ return InteractionsAPIStreamingResponse(**parsed_chunk)
+
+ # GET / DELETE / CANCEL - just build URLs, responses match spec directly
+
+ def transform_get_interaction_request(
+ self,
+ interaction_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """GET /{api_version}/interactions/{interaction_id}"""
+ resolved_api_base = GeminiModelInfo.get_api_base(api_base)
+ api_key = GeminiModelInfo.get_api_key(litellm_params.api_key)
+ if not api_key:
+ raise ValueError("Google API key is required")
+ return f"{resolved_api_base}/{self.api_version}/interactions/{interaction_id}?key={api_key}", {}
+
+ def transform_get_interaction_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> InteractionsAPIResponse:
+ try:
+ raw_json = raw_response.json()
+ except Exception:
+ raise GeminiError(
+ message=raw_response.text,
+ status_code=raw_response.status_code,
+ headers=dict(raw_response.headers),
+ )
+ response = InteractionsAPIResponse(**raw_json)
+ response._hidden_params["headers"] = dict(raw_response.headers)
+ return response
+
+ def transform_delete_interaction_request(
+ self,
+ interaction_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """DELETE /{api_version}/interactions/{interaction_id}"""
+ resolved_api_base = GeminiModelInfo.get_api_base(api_base)
+ api_key = GeminiModelInfo.get_api_key(litellm_params.api_key)
+ if not api_key:
+ raise ValueError("Google API key is required")
+ return f"{resolved_api_base}/{self.api_version}/interactions/{interaction_id}?key={api_key}", {}
+
+ def transform_delete_interaction_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ interaction_id: str,
+ ) -> DeleteInteractionResult:
+ if 200 <= raw_response.status_code < 300:
+ return DeleteInteractionResult(success=True, id=interaction_id)
+ raise GeminiError(
+ message=raw_response.text,
+ status_code=raw_response.status_code,
+ headers=dict(raw_response.headers),
+ )
+
+ def transform_cancel_interaction_request(
+ self,
+ interaction_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[str, Dict]:
+ """POST /{api_version}/interactions/{interaction_id}:cancel (if supported)"""
+ resolved_api_base = GeminiModelInfo.get_api_base(api_base)
+ api_key = GeminiModelInfo.get_api_key(litellm_params.api_key)
+ if not api_key:
+ raise ValueError("Google API key is required")
+ return f"{resolved_api_base}/{self.api_version}/interactions/{interaction_id}:cancel?key={api_key}", {}
+
+ def transform_cancel_interaction_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> CancelInteractionResult:
+ try:
+ raw_json = raw_response.json()
+ except Exception:
+ raise GeminiError(
+ message=raw_response.text,
+ status_code=raw_response.status_code,
+ headers=dict(raw_response.headers),
+ )
+ return CancelInteractionResult(**raw_json)
diff --git a/litellm/types/interactions/README.md b/litellm/types/interactions/README.md
new file mode 100644
index 00000000000..a16744ce016
--- /dev/null
+++ b/litellm/types/interactions/README.md
@@ -0,0 +1,48 @@
+# Interactions API Types
+
+This directory contains type definitions for the Google Interactions API.
+
+## Generated Types
+
+The `generated.py` file is auto-generated from the official OpenAPI spec:
+https://ai.google.dev/static/api/interactions.openapi.json
+
+### How to Regenerate
+
+When the API spec changes, regenerate the types with:
+
+```bash
+pip install datamodel-code-generator
+
+datamodel-codegen \
+ --url "https://ai.google.dev/static/api/interactions.openapi.json" \
+ --output litellm/types/interactions/generated.py \
+ --output-model-type pydantic_v2.BaseModel \
+ --target-python-version 3.9
+```
+
+Then add the LiteLLM-specific types at the bottom of the generated file:
+- `InteractionsAPIResponse`
+- `InteractionsAPIStreamingResponse`
+- `DeleteInteractionResult`
+- `CancelInteractionResult`
+
+### Key Types
+
+**Request Types:**
+- `CreateModelInteractionParams` - For model interactions
+- `CreateAgentInteractionParams` - For agent interactions
+
+**Content Types:**
+- `Content` - Union of all content types (text, image, audio, etc.)
+- `TextContent` - Text content with `type: "text"`
+- `Turn` - A turn in multi-turn conversation with `role` and `content`
+
+**Tool Types:**
+- `Tool` - Union of all tool types
+- `Function` - Function tool declaration
+
+**Response Types:**
+- `InteractionsAPIResponse` - LiteLLM response wrapper
+- `InteractionsAPIStreamingResponse` - Streaming response chunk
+
diff --git a/litellm/types/interactions/__init__.py b/litellm/types/interactions/__init__.py
new file mode 100644
index 00000000000..a3acdc4cb1f
--- /dev/null
+++ b/litellm/types/interactions/__init__.py
@@ -0,0 +1,127 @@
+"""
+Type definitions for Google Interactions API
+
+Auto-generated from OpenAPI spec: https://ai.google.dev/static/api/interactions.openapi.json
+See README.md for regeneration instructions.
+"""
+
+from litellm.types.interactions.generated import (
+ AgentOption,
+ Annotation,
+ AudioContent,
+ CancelInteractionResult,
+ CodeExecution,
+ CodeExecutionCallContent,
+ CodeExecutionResultContent,
+ ComputerUse,
+ Content,
+ ContentDelta,
+ ContentStart,
+ ContentStop,
+ CreateAgentInteractionParams,
+ CreateModelInteractionParams,
+ DeepResearchAgentConfig,
+ DeleteInteractionResult,
+ DocumentContent,
+ DynamicAgentConfig,
+ ErrorEvent,
+ FileSearch,
+ FileSearchResultContent,
+ Function,
+ FunctionCallContent,
+ FunctionResultContent,
+ GenerationConfig,
+ GoogleSearch,
+ GoogleSearchCallContent,
+ GoogleSearchResultContent,
+ ImageContent,
+ Interaction,
+ InteractionEvent,
+ InteractionInput,
+ InteractionsAPIOptionalRequestParams,
+ InteractionsAPIResponse,
+ InteractionsAPIStreamingResponse,
+ InteractionSseEvent,
+ InteractionTool,
+ InteractionToolChoiceConfig,
+ McpServer,
+ McpServerToolCallContent,
+ McpServerToolResultContent,
+ ModelOption,
+ ResponseModality,
+)
+from litellm.types.interactions.generated import (
+ Status3 as InteractionStatus, # Main request/response types; Content types; Turn for multi-turn conversations; Tool types; Config types; Usage; Status enum; Events for streaming; Agent configs; Model/Agent options; Response modality; Annotation; LiteLLM types; Backwards compat aliases
+)
+from litellm.types.interactions.generated import (
+ TextContent,
+ ThoughtContent,
+ Tool,
+ ToolChoiceConfig,
+ Turn,
+ UrlContext,
+ UrlContextCallContent,
+ UrlContextResultContent,
+ Usage,
+ VideoContent,
+)
+
+__all__ = [
+ # Generated types
+ "CreateModelInteractionParams",
+ "CreateAgentInteractionParams",
+ "Interaction",
+ "Content",
+ "TextContent",
+ "ImageContent",
+ "AudioContent",
+ "DocumentContent",
+ "VideoContent",
+ "ThoughtContent",
+ "FunctionCallContent",
+ "FunctionResultContent",
+ "CodeExecutionCallContent",
+ "CodeExecutionResultContent",
+ "UrlContextCallContent",
+ "UrlContextResultContent",
+ "GoogleSearchCallContent",
+ "GoogleSearchResultContent",
+ "McpServerToolCallContent",
+ "McpServerToolResultContent",
+ "FileSearchResultContent",
+ "Turn",
+ "Tool",
+ "Function",
+ "GoogleSearch",
+ "CodeExecution",
+ "UrlContext",
+ "ComputerUse",
+ "McpServer",
+ "FileSearch",
+ "GenerationConfig",
+ "ToolChoiceConfig",
+ "Usage",
+ "InteractionStatus",
+ "InteractionEvent",
+ "InteractionSseEvent",
+ "ContentStart",
+ "ContentDelta",
+ "ContentStop",
+ "ErrorEvent",
+ "DynamicAgentConfig",
+ "DeepResearchAgentConfig",
+ "ModelOption",
+ "AgentOption",
+ "ResponseModality",
+ "Annotation",
+ # LiteLLM types
+ "InteractionInput",
+ "InteractionsAPIResponse",
+ "InteractionsAPIStreamingResponse",
+ "DeleteInteractionResult",
+ "CancelInteractionResult",
+ "InteractionsAPIOptionalRequestParams",
+ # Backwards compat
+ "InteractionTool",
+ "InteractionToolChoiceConfig",
+]
diff --git a/litellm/types/interactions/generated.py b/litellm/types/interactions/generated.py
new file mode 100644
index 00000000000..72693e8f188
--- /dev/null
+++ b/litellm/types/interactions/generated.py
@@ -0,0 +1,1254 @@
+# generated by datamodel-codegen:
+# filename: https://ai.google.dev/static/api/interactions.openapi.json
+# timestamp: 2025-12-16T21:25:12+00:00
+
+from __future__ import annotations
+
+from enum import Enum
+from typing import Any, Dict, List, Literal, Optional, Union
+
+from pydantic import AwareDatetime, Base64Str, BaseModel, Field, RootModel
+
+
+class Annotation(BaseModel):
+ start_index: Optional[int] = Field(
+ None,
+ description='Start of segment of the response that is attributed to this source.\n\nIndex indicates the start of the segment, measured in bytes.',
+ )
+ end_index: Optional[int] = Field(
+ None, description='End of the attributed segment, exclusive.'
+ )
+ source: Optional[str] = Field(
+ None,
+ description='Source attributed for a portion of the text. Could be a URL, title, or\nother identifier.',
+ )
+
+
+class DocumentContent(BaseModel):
+ data: Optional[Base64Str] = None
+ uri: Optional[str] = None
+ mime_type: Optional[str] = None
+ type: Literal['document'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+
+
+class FunctionCallContent(BaseModel):
+ name: str = Field(..., description='The name of the tool to call.')
+ arguments: Dict[str, Any] = Field(
+ ..., description='The arguments to pass to the function.'
+ )
+ type: Literal['function_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: str = Field(..., description='A unique ID for this specific tool call.')
+
+
+class Language(Enum):
+ python = 'python'
+
+
+class CodeExecutionCallArguments(BaseModel):
+ language: Optional[Language] = Field(
+ None, description='Programming language of the `code`.'
+ )
+ code: Optional[str] = Field(None, description='The code to be executed.')
+
+
+class UrlContextCallArguments(BaseModel):
+ urls: Optional[List[str]] = Field(None, description='The URLs to fetch.')
+
+
+class McpServerToolCallContent(BaseModel):
+ name: str = Field(..., description='The name of the tool which was called.')
+ server_name: str = Field(..., description='The name of the used MCP server.')
+ arguments: Dict[str, Any] = Field(
+ ..., description='The JSON object of arguments for the function.'
+ )
+ type: Literal['mcp_server_tool_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: str = Field(..., description='A unique ID for this specific tool call.')
+
+
+class GoogleSearchCallArguments(BaseModel):
+ queries: Optional[List[str]] = Field(
+ None, description='Web search queries for the following-up web search.'
+ )
+
+
+class CodeExecutionResultContent(BaseModel):
+ result: Optional[str] = Field(None, description='The output of the code execution.')
+ is_error: Optional[bool] = Field(
+ None, description='Whether the code execution resulted in an error.'
+ )
+ signature: Optional[str] = Field(
+ None, description='A signature hash for backend validation.'
+ )
+ type: Literal['code_execution_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ call_id: Optional[str] = Field(
+ None, description='ID to match the ID from the code execution call block.'
+ )
+
+
+class Status(Enum):
+ success = 'success'
+ error = 'error'
+ paywall = 'paywall'
+ unsafe = 'unsafe'
+
+
+class UrlContextResult(BaseModel):
+ url: Optional[str] = Field(None, description='The URL that was fetched.')
+ status: Optional[Status] = Field(
+ None, description='The status of the URL retrieval.'
+ )
+
+
+class GoogleSearchResult(BaseModel):
+ url: Optional[str] = Field(None, description='URI reference of the search result.')
+ title: Optional[str] = Field(None, description='Title of the search result.')
+ rendered_content: Optional[str] = Field(
+ None,
+ description='Web content snippet that can be embedded in a web page or an app webview.',
+ )
+
+
+class FileSearchResult(BaseModel):
+ title: Optional[str] = Field(None, description='The title of the search result.')
+ text: Optional[str] = Field(None, description='The text of the search result.')
+ file_search_store: Optional[str] = Field(
+ None, description='The name of the file search store.'
+ )
+
+
+class SpeechConfig(BaseModel):
+ voice: Optional[str] = Field(None, description='The voice of the speaker.')
+ language: Optional[str] = Field(None, description='The language of the speech.')
+ speaker: Optional[str] = Field(
+ None,
+ description="The speaker's name, it should match the speaker name given in the prompt.",
+ )
+
+
+class DynamicAgentConfig(BaseModel):
+ type: Literal['dynamic'] = Field(
+ 'dynamic',
+ description='Used as the OpenAPI type discriminator for the content oneof.',
+ )
+
+
+class Function(BaseModel):
+ name: Optional[str] = Field(None, description='The name of the function.')
+ description: Optional[str] = Field(
+ None, description='A description of the function.'
+ )
+ parameters: Optional[Any] = Field(
+ None, description="The JSON Schema for the function's parameters."
+ )
+ type: Literal['function']
+
+
+class CodeExecution(BaseModel):
+ type: Literal['code_execution']
+
+
+class UrlContext(BaseModel):
+ type: Literal['url_context']
+
+
+class Environment(Enum):
+ browser = 'browser'
+
+
+class ComputerUse(BaseModel):
+ type: Literal['computer_use']
+ environment: Optional[Environment] = Field(
+ None, description='The environment being operated.'
+ )
+ excludedPredefinedFunctions: Optional[List[str]] = Field(
+ None,
+ description='The list of predefined functions that are excluded from the model call.',
+ )
+
+
+class GoogleSearch(BaseModel):
+ type: Literal['google_search']
+
+
+class FileSearch(BaseModel):
+ file_search_store_names: Optional[List[str]] = Field(
+ None, description='The file search store names to search.'
+ )
+ top_k: Optional[int] = Field(
+ None, description='The number of semantic retrieval chunks to retrieve.'
+ )
+ metadata_filter: Optional[str] = Field(
+ None,
+ description='Metadata filter to apply to the semantic retrieval documents and chunks.',
+ )
+ type: Literal['file_search']
+
+
+class EventType(Enum):
+ interaction_start = 'interaction.start'
+ interaction_complete = 'interaction.complete'
+
+
+class Status1(Enum):
+ in_progress = 'in_progress'
+ requires_action = 'requires_action'
+ completed = 'completed'
+ failed = 'failed'
+ cancelled = 'cancelled'
+
+
+class InteractionStatusUpdate(BaseModel):
+ interaction_id: Optional[str] = None
+ status: Optional[Status1] = None
+ event_type: Literal['interaction.status_update'] = 'interaction.status_update'
+ event_id: Optional[str] = Field(
+ None,
+ description='The event_id token to be used to resume the interaction stream, from\nthis event.',
+ )
+
+
+class TextDelta(BaseModel):
+ text: Optional[str] = None
+ type: Literal['text'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ annotations: Optional[List[Annotation]] = Field(
+ None, description='Citation information for model-generated content.'
+ )
+
+
+class DocumentDelta(BaseModel):
+ data: Optional[Base64Str] = None
+ uri: Optional[str] = None
+ mime_type: Optional[str] = None
+ type: Literal['document'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+
+
+class ThoughtSignatureDelta(BaseModel):
+ signature: Optional[Base64Str] = Field(
+ None,
+ description='Signature to match the backend source to be part of the generation.',
+ )
+ type: Literal['thought_signature'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+
+
+class FunctionCallDelta(BaseModel):
+ name: Optional[str] = None
+ arguments: Optional[Dict[str, Any]] = None
+ type: Literal['function_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: Optional[str] = Field(
+ None, description='A unique ID for this specific tool call.'
+ )
+
+
+class CodeExecutionCallDelta(BaseModel):
+ arguments: Optional[CodeExecutionCallArguments] = None
+ type: Literal['code_execution_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: Optional[str] = Field(
+ None, description='A unique ID for this specific tool call.'
+ )
+
+
+class UrlContextCallDelta(BaseModel):
+ arguments: Optional[UrlContextCallArguments] = None
+ type: Literal['url_context_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: Optional[str] = Field(
+ None, description='A unique ID for this specific tool call.'
+ )
+
+
+class GoogleSearchCallDelta(BaseModel):
+ arguments: Optional[GoogleSearchCallArguments] = None
+ type: Literal['google_search_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: Optional[str] = Field(
+ None, description='A unique ID for this specific tool call.'
+ )
+
+
+class McpServerToolCallDelta(BaseModel):
+ name: Optional[str] = None
+ server_name: Optional[str] = None
+ arguments: Optional[Dict[str, Any]] = None
+ type: Literal['mcp_server_tool_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: Optional[str] = Field(
+ None, description='A unique ID for this specific tool call.'
+ )
+
+
+class CodeExecutionResultDelta(BaseModel):
+ result: Optional[str] = None
+ is_error: Optional[bool] = None
+ signature: Optional[str] = None
+ type: Literal['code_execution_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ call_id: Optional[str] = Field(
+ None, description='ID to match the ID from the function call block.'
+ )
+
+
+class UrlContextResultDelta(BaseModel):
+ signature: Optional[str] = None
+ result: Optional[List[UrlContextResult]] = None
+ is_error: Optional[bool] = None
+ type: Literal['url_context_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ call_id: Optional[str] = Field(
+ None, description='ID to match the ID from the function call block.'
+ )
+
+
+class GoogleSearchResultDelta(BaseModel):
+ signature: Optional[str] = None
+ result: Optional[List[GoogleSearchResult]] = None
+ is_error: Optional[bool] = None
+ type: Literal['google_search_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ call_id: Optional[str] = Field(
+ None, description='ID to match the ID from the function call block.'
+ )
+
+
+class FileSearchResultDelta(BaseModel):
+ result: Optional[List[FileSearchResult]] = None
+ type: Literal['file_search_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+
+
+class ContentStop(BaseModel):
+ index: Optional[int] = None
+ event_type: Literal['content.stop'] = 'content.stop'
+ event_id: Optional[str] = Field(
+ None,
+ description='The event_id token to be used to resume the interaction stream, from\nthis event.',
+ )
+
+
+class Error(BaseModel):
+ code: Optional[str] = Field(
+ None, description='A URI that identifies the error type.'
+ )
+ message: Optional[str] = Field(None, description='A human-readable error message.')
+
+
+class MediaResolution(Enum):
+ low = 'low'
+ medium = 'medium'
+ high = 'high'
+
+
+class ToolChoiceType(Enum):
+ auto = 'auto'
+ any = 'any'
+ none = 'none'
+ validated = 'validated'
+
+
+class ThinkingLevel(Enum):
+ low = 'low'
+ high = 'high'
+
+
+class ThinkingSummaries(Enum):
+ auto = 'auto'
+ none = 'none'
+
+
+class ResponseModality(Enum):
+ text = 'text'
+ image = 'image'
+ audio = 'audio'
+
+
+class Status3(Enum):
+ UNSPECIFIED = 'UNSPECIFIED'
+ IN_PROGRESS = 'IN_PROGRESS'
+ REQUIRES_ACTION = 'REQUIRES_ACTION'
+ COMPLETED = 'COMPLETED'
+ FAILED = 'FAILED'
+ CANCELLED = 'CANCELLED'
+
+
+class ModelOption(RootModel[str]):
+ root: str = Field(
+ ...,
+ description='The model that will complete your prompt.\\n\\nSee [models](https://ai.google.dev/gemini-api/docs/models) for additional details.',
+ title='Model',
+ )
+
+
+class AgentOption(RootModel[str]):
+ root: str = Field(..., description='The agent to interact with.', title='Agent')
+
+
+class ImageMimeTypeOption(RootModel[str]):
+ root: str = Field(
+ ..., description='The mime type of the image.', title='ImageMimeType'
+ )
+
+
+class AudioMimeTypeOption(RootModel[str]):
+ root: str = Field(
+ ..., description='The mime type of the audio.', title='AudioMimeType'
+ )
+
+
+class VideoMimeTypeOption(RootModel[str]):
+ root: str = Field(
+ ..., description='The mime type of the video.', title='VideoMimeType'
+ )
+
+
+class TextContent(BaseModel):
+ text: Optional[str] = Field(None, description='The text content.')
+ type: Literal['text'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ annotations: Optional[List[Annotation]] = Field(
+ None, description='Citation information for model-generated content.'
+ )
+
+
+class ImageContent(BaseModel):
+ data: Optional[Base64Str] = None
+ uri: Optional[str] = None
+ mime_type: Optional[ImageMimeTypeOption] = None
+ type: Literal['image'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ resolution: Optional[MediaResolution] = Field(
+ None, description='The resolution of the media.'
+ )
+
+
+class AudioContent(BaseModel):
+ data: Optional[Base64Str] = None
+ uri: Optional[str] = None
+ mime_type: Optional[AudioMimeTypeOption] = None
+ type: Literal['audio'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+
+
+class VideoContent(BaseModel):
+ data: Optional[Base64Str] = None
+ uri: Optional[str] = None
+ mime_type: Optional[VideoMimeTypeOption] = None
+ type: Literal['video'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ resolution: Optional[MediaResolution] = Field(
+ None, description='The resolution of the media.'
+ )
+
+
+class ThoughtSummary1(RootModel[Union[TextContent, ImageContent]]):
+ root: Union[TextContent, ImageContent] = Field(..., discriminator='type')
+
+
+class ThoughtSummary(RootModel[List[ThoughtSummary1]]):
+ root: List[ThoughtSummary1] = Field(..., description='A summary of the thought.')
+
+
+class CodeExecutionCallContent(BaseModel):
+ arguments: Optional[CodeExecutionCallArguments] = Field(
+ None, description='The arguments to pass to the code execution.'
+ )
+ type: Literal['code_execution_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: Optional[str] = Field(
+ None, description='A unique ID for this specific tool call.'
+ )
+
+
+class UrlContextCallContent(BaseModel):
+ arguments: Optional[UrlContextCallArguments] = Field(
+ None, description='The arguments to pass to the URL context.'
+ )
+ type: Literal['url_context_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: Optional[str] = Field(
+ None, description='A unique ID for this specific tool call.'
+ )
+
+
+class GoogleSearchCallContent(BaseModel):
+ arguments: Optional[GoogleSearchCallArguments] = Field(
+ None, description='The arguments to pass to Google Search.'
+ )
+ type: Literal['google_search_call'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ id: Optional[str] = Field(
+ None, description='A unique ID for this specific tool call.'
+ )
+
+
+class Result(BaseModel):
+ items: Optional[List[Union[str, ImageContent]]] = None
+
+
+class FunctionResultContent(BaseModel):
+ name: Optional[str] = Field(
+ None, description='The name of the tool that was called.'
+ )
+ is_error: Optional[bool] = Field(
+ None, description='Whether the tool call resulted in an error.'
+ )
+ type: Literal['function_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ result: Union[Result, Dict[str, Any], str] = Field(
+ ..., description='The result of the tool call.'
+ )
+ call_id: str = Field(
+ ..., description='ID to match the ID from the function call block.'
+ )
+
+
+class UrlContextResultContent(BaseModel):
+ signature: Optional[str] = Field(
+ None, description='The signature of the URL context result.'
+ )
+ result: Optional[List[UrlContextResult]] = Field(
+ None, description='The results of the URL context.'
+ )
+ is_error: Optional[bool] = Field(
+ None, description='Whether the URL context resulted in an error.'
+ )
+ type: Literal['url_context_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ call_id: Optional[str] = Field(
+ None, description='ID to match the ID from the url context call block.'
+ )
+
+
+class GoogleSearchResultContent(BaseModel):
+ signature: Optional[str] = Field(
+ None, description='The signature of the Google Search result.'
+ )
+ result: Optional[List[GoogleSearchResult]] = Field(
+ None, description='The results of the Google Search.'
+ )
+ is_error: Optional[bool] = Field(
+ None, description='Whether the Google Search resulted in an error.'
+ )
+ type: Literal['google_search_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ call_id: Optional[str] = Field(
+ None, description='ID to match the ID from the google search call block.'
+ )
+
+
+class McpServerToolResultContent(BaseModel):
+ name: Optional[str] = Field(
+ None,
+ description='Name of the tool which is called for this specific tool call.',
+ )
+ server_name: Optional[str] = Field(
+ None, description='The name of the used MCP server.'
+ )
+ type: Literal['mcp_server_tool_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ result: Union[Result, Dict[str, Any], str] = Field(
+ ..., description='The result of the tool call.'
+ )
+ call_id: str = Field(
+ ..., description='ID to match the ID from the MCP server tool call block.'
+ )
+
+
+class FileSearchResultContent(BaseModel):
+ result: Optional[List[FileSearchResult]] = Field(
+ None, description='The results of the File Search.'
+ )
+ type: Literal['file_search_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+
+
+class AllowedTools(BaseModel):
+ mode: Optional[ToolChoiceType] = Field(
+ None, description='The mode of the tool choice.'
+ )
+ tools: Optional[List[str]] = Field(
+ None, description='The names of the allowed tools.'
+ )
+
+
+class DeepResearchAgentConfig(BaseModel):
+ type: Literal['deep-research'] = Field(
+ 'deep-research',
+ description='Used as the OpenAPI type discriminator for the content oneof.',
+ )
+ thinking_summaries: Optional[ThinkingSummaries] = Field(
+ None, description='Whether to include thought summaries in the response.'
+ )
+
+
+class McpServer(BaseModel):
+ type: Literal['mcp_server']
+ name: Optional[str] = Field(None, description='The name of the MCPServer.')
+ url: Optional[str] = Field(
+ None,
+ description='The full URL for the MCPServer endpoint.\nExample: "https://api.example.com/mcp"',
+ )
+ headers: Optional[Dict[str, str]] = Field(
+ None,
+ description='Optional: Fields for authentication headers, timeouts, etc., if needed.',
+ )
+ allowed_tools: Optional[List[AllowedTools]] = Field(
+ None, description='The allowed tools.'
+ )
+
+
+class ModalityTokens(BaseModel):
+ modality: Optional[ResponseModality] = Field(
+ None, description='The modality associated with the token count.'
+ )
+ tokens: Optional[int] = Field(
+ None, description='Number of tokens for the modality.'
+ )
+
+
+class ImageDelta(BaseModel):
+ data: Optional[Base64Str] = None
+ uri: Optional[str] = None
+ mime_type: Optional[ImageMimeTypeOption] = None
+ type: Literal['image'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ resolution: Optional[MediaResolution] = Field(
+ None, description='The resolution of the media.'
+ )
+
+
+class AudioDelta(BaseModel):
+ data: Optional[Base64Str] = None
+ uri: Optional[str] = None
+ mime_type: Optional[AudioMimeTypeOption] = None
+ type: Literal['audio'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+
+
+class VideoDelta(BaseModel):
+ data: Optional[Base64Str] = None
+ uri: Optional[str] = None
+ mime_type: Optional[VideoMimeTypeOption] = None
+ type: Literal['video'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ resolution: Optional[MediaResolution] = Field(
+ None, description='The resolution of the media.'
+ )
+
+
+class ThoughtSummaryDelta(BaseModel):
+ type: Literal['thought_summary'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ content: Optional[Union[TextContent, ImageContent]] = Field(
+ None, discriminator='type'
+ )
+
+
+class FunctionResultDelta(BaseModel):
+ name: Optional[str] = None
+ is_error: Optional[bool] = None
+ type: Literal['function_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ result: Optional[Union[Result, str]] = Field(
+ None, description='Tool call result delta.'
+ )
+ call_id: Optional[str] = Field(
+ None, description='ID to match the ID from the function call block.'
+ )
+
+
+class McpServerToolResultDelta(BaseModel):
+ name: Optional[str] = None
+ server_name: Optional[str] = None
+ type: Literal['mcp_server_tool_result'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ result: Optional[Union[Result, str]] = Field(
+ None, description='Tool call result delta.'
+ )
+ call_id: Optional[str] = Field(
+ None, description='ID to match the ID from the function call block.'
+ )
+
+
+class ErrorEvent(BaseModel):
+ event_type: Literal['error'] = 'error'
+ error: Optional[Error] = None
+ event_id: Optional[str] = Field(
+ None,
+ description='The event_id token to be used to resume the interaction stream, from\nthis event.',
+ )
+
+
+class ToolChoiceConfig(BaseModel):
+ allowed_tools: Optional[AllowedTools] = None
+
+
+class Tool(
+ RootModel[
+ Union[
+ Function,
+ GoogleSearch,
+ CodeExecution,
+ UrlContext,
+ ComputerUse,
+ McpServer,
+ FileSearch,
+ ]
+ ]
+):
+ root: Union[
+ Function,
+ GoogleSearch,
+ CodeExecution,
+ UrlContext,
+ ComputerUse,
+ McpServer,
+ FileSearch,
+ ] = Field(..., discriminator='type')
+
+
+class ThoughtContent(BaseModel):
+ signature: Optional[Base64Str] = Field(
+ None,
+ description='Signature to match the backend source to be part of the generation.',
+ )
+ type: Literal['thought'] = Field(
+ ..., description='Used as the OpenAPI type discriminator for the content oneof.'
+ )
+ summary: Optional[ThoughtSummary] = Field(
+ None, description='A summary of the thought.'
+ )
+
+
+class ToolChoice(RootModel[Union[ToolChoiceType, ToolChoiceConfig]]):
+ root: Union[ToolChoiceType, ToolChoiceConfig] = Field(
+ ..., description='The configuration for tool choice.'
+ )
+
+
+class Usage(BaseModel):
+ total_input_tokens: Optional[int] = Field(
+ None, description='Number of tokens in the prompt (context).'
+ )
+ input_tokens_by_modality: Optional[List[ModalityTokens]] = Field(
+ None, description='A breakdown of input token usage by modality.'
+ )
+ total_cached_tokens: Optional[int] = Field(
+ None,
+ description='Number of tokens in the cached part of the prompt (the cached content).',
+ )
+ cached_tokens_by_modality: Optional[List[ModalityTokens]] = Field(
+ None, description='A breakdown of cached token usage by modality.'
+ )
+ total_output_tokens: Optional[int] = Field(
+ None, description='Total number of tokens across all the generated responses.'
+ )
+ output_tokens_by_modality: Optional[List[ModalityTokens]] = Field(
+ None, description='A breakdown of output token usage by modality.'
+ )
+ total_tool_use_tokens: Optional[int] = Field(
+ None, description='Number of tokens present in tool-use prompt(s).'
+ )
+ tool_use_tokens_by_modality: Optional[List[ModalityTokens]] = Field(
+ None, description='A breakdown of tool-use token usage by modality.'
+ )
+ total_reasoning_tokens: Optional[int] = Field(
+ None, description='Number of tokens of thoughts for thinking models.'
+ )
+ total_tokens: Optional[int] = Field(
+ None,
+ description='Total token count for the interaction request (prompt + responses + other\ninternal tokens).',
+ )
+
+
+class ContentDelta(BaseModel):
+ index: Optional[int] = None
+ event_type: Literal['content.delta'] = 'content.delta'
+ event_id: Optional[str] = Field(
+ None,
+ description='The event_id token to be used to resume the interaction stream, from\nthis event.',
+ )
+ delta: Optional[
+ Union[
+ TextDelta,
+ ImageDelta,
+ AudioDelta,
+ DocumentDelta,
+ VideoDelta,
+ ThoughtSummaryDelta,
+ ThoughtSignatureDelta,
+ FunctionCallDelta,
+ FunctionResultDelta,
+ CodeExecutionCallDelta,
+ CodeExecutionResultDelta,
+ UrlContextCallDelta,
+ UrlContextResultDelta,
+ GoogleSearchCallDelta,
+ GoogleSearchResultDelta,
+ McpServerToolCallDelta,
+ McpServerToolResultDelta,
+ FileSearchResultDelta,
+ ]
+ ] = Field(None, discriminator='type')
+
+
+class Content(
+ RootModel[
+ Union[
+ TextContent,
+ ImageContent,
+ AudioContent,
+ DocumentContent,
+ VideoContent,
+ ThoughtContent,
+ FunctionCallContent,
+ FunctionResultContent,
+ CodeExecutionCallContent,
+ CodeExecutionResultContent,
+ UrlContextCallContent,
+ UrlContextResultContent,
+ GoogleSearchCallContent,
+ GoogleSearchResultContent,
+ McpServerToolCallContent,
+ McpServerToolResultContent,
+ FileSearchResultContent,
+ ]
+ ]
+):
+ root: Union[
+ TextContent,
+ ImageContent,
+ AudioContent,
+ DocumentContent,
+ VideoContent,
+ ThoughtContent,
+ FunctionCallContent,
+ FunctionResultContent,
+ CodeExecutionCallContent,
+ CodeExecutionResultContent,
+ UrlContextCallContent,
+ UrlContextResultContent,
+ GoogleSearchCallContent,
+ GoogleSearchResultContent,
+ McpServerToolCallContent,
+ McpServerToolResultContent,
+ FileSearchResultContent,
+ ] = Field(..., description='The content of the response.', discriminator='type')
+
+
+class Turn(BaseModel):
+ role: Optional[str] = Field(
+ None,
+ description='The originator of this turn. Must be user for input or model for\nmodel output.',
+ )
+ content: Optional[Union[str, List[Content]]] = Field(
+ None, description='The content of the turn.'
+ )
+
+
+class GenerationConfig(BaseModel):
+ temperature: Optional[float] = Field(
+ None, description='Controls the randomness of the output.'
+ )
+ top_p: Optional[float] = Field(
+ None,
+ description='The maximum cumulative probability of tokens to consider when sampling.',
+ )
+ seed: Optional[int] = Field(
+ None, description='Seed used in decoding for reproducibility.'
+ )
+ stop_sequences: Optional[List[str]] = Field(
+ None,
+ description='A list of character sequences that will stop output interaction.',
+ )
+ tool_choice: Optional[ToolChoice] = Field(
+ None, description='The tool choice for the interaction.'
+ )
+ thinking_level: Optional[ThinkingLevel] = Field(
+ None, description='The level of thought tokens that the model should generate.'
+ )
+ thinking_summaries: Optional[ThinkingSummaries] = Field(
+ None, description='Whether to include thought summaries in the response.'
+ )
+ max_output_tokens: Optional[int] = Field(
+ None, description='The maximum number of tokens to include in the response.'
+ )
+ speech_config: Optional[List[SpeechConfig]] = Field(
+ None, description='Configuration for speech interaction.'
+ )
+
+
+class ContentStart(BaseModel):
+ index: Optional[int] = None
+ content: Optional[Content] = None
+ event_type: Literal['content.start'] = 'content.start'
+ event_id: Optional[str] = Field(
+ None,
+ description='The event_id token to be used to resume the interaction stream, from\nthis event.',
+ )
+
+
+class Interaction(BaseModel):
+ model: Optional[ModelOption] = Field(
+ None, description='The name of the `Model` used for generating the interaction.'
+ )
+ agent: Optional[AgentOption] = Field(
+ None, description='The name of the `Agent` used for generating the interaction.'
+ )
+ id: str = Field(
+ ...,
+ description='Output only. A unique identifier for the interaction completion.',
+ )
+ status: Status1 = Field(
+ ..., description='Output only. The status of the interaction.'
+ )
+ created: Optional[AwareDatetime] = Field(
+ None,
+ description='Output only. The time at which the response was created in ISO 8601 format\n(YYYY-MM-DDThh:mm:ssZ).',
+ )
+ updated: Optional[AwareDatetime] = Field(
+ None,
+ description='Output only. The time at which the response was last updated in ISO 8601 format\n(YYYY-MM-DDThh:mm:ssZ).',
+ )
+ role: Optional[str] = Field(
+ None, description='Output only. The role of the interaction.'
+ )
+ outputs: Optional[List[Content]] = Field(
+ None, description='Output only. Responses from the model.'
+ )
+ system_instruction: Optional[str] = Field(
+ None, description='System instruction for the interaction.'
+ )
+ tools: Optional[List[Tool]] = Field(
+ None,
+ description='A list of tool declarations the model may call during interaction.',
+ )
+ background: Optional[bool] = Field(
+ None, description='Whether to run the model interaction in the background.'
+ )
+ object: Literal['interaction'] = Field(
+ 'interaction',
+ description='Output only. The object type of the interaction. Always set to `interaction`.',
+ )
+ usage: Optional[Usage] = Field(
+ None,
+ description="Output only. Statistics on the interaction request's token usage.",
+ )
+ response_modalities: Optional[List[ResponseModality]] = Field(
+ None,
+ description='The requested modalities of the response (TEXT, IMAGE, AUDIO).',
+ )
+ response_format: Optional[Any] = Field(
+ None,
+ description='Enforces that the generated response is a JSON object that complies with\nthe JSON schema specified in this field.',
+ )
+ response_mime_type: Optional[str] = Field(
+ None,
+ description='The mime type of the response. This is required if response_format is set.',
+ )
+ previous_interaction_id: Optional[str] = Field(
+ None, description='The ID of the previous interaction, if any.'
+ )
+ input: Optional[Union[str, List[Content], List[Turn], Content]] = Field(
+ None, description='The inputs for the interaction.'
+ )
+ generation_config: Optional[GenerationConfig] = Field(
+ None,
+ description='Input only. Configuration parameters for the model interaction.',
+ )
+ agent_config: Optional[Union[DynamicAgentConfig, DeepResearchAgentConfig]] = Field(
+ None, description='Configuration for the agent.', discriminator='type'
+ )
+
+
+class CreateModelInteractionParams(BaseModel):
+ model: ModelOption = Field(
+ ..., description='The name of the `Model` used for generating the interaction.'
+ )
+ stream: Optional[bool] = Field(
+ None, description='Input only. Whether the interaction will be streamed.'
+ )
+ store: Optional[bool] = Field(
+ None,
+ description='Input only. Whether to store the response and request for later retrieval.',
+ )
+ id: Optional[str] = Field(
+ None,
+ description='Output only. A unique identifier for the interaction completion.',
+ )
+ status: Optional[Status3] = Field(
+ None, description='Output only. The status of the interaction.'
+ )
+ created: Optional[AwareDatetime] = Field(
+ None,
+ description='Output only. The time at which the response was created in ISO 8601 format\n(YYYY-MM-DDThh:mm:ssZ).',
+ )
+ updated: Optional[AwareDatetime] = Field(
+ None,
+ description='Output only. The time at which the response was last updated in ISO 8601 format\n(YYYY-MM-DDThh:mm:ssZ).',
+ )
+ role: Optional[str] = Field(
+ None, description='Output only. The role of the interaction.'
+ )
+ outputs: Optional[List[Content]] = Field(
+ None, description='Output only. Responses from the model.'
+ )
+ system_instruction: Optional[str] = Field(
+ None, description='System instruction for the interaction.'
+ )
+ tools: Optional[List[Tool]] = Field(
+ None,
+ description='A list of tool declarations the model may call during interaction.',
+ )
+ background: Optional[bool] = Field(
+ None, description='Whether to run the model interaction in the background.'
+ )
+ usage: Optional[Usage] = Field(
+ None,
+ description="Output only. Statistics on the interaction request's token usage.",
+ )
+ response_modalities: Optional[List[ResponseModality]] = Field(
+ None,
+ description='The requested modalities of the response (TEXT, IMAGE, AUDIO).',
+ )
+ response_format: Optional[Any] = Field(
+ None,
+ description='Enforces that the generated response is a JSON object that complies with\nthe JSON schema specified in this field.',
+ )
+ response_mime_type: Optional[str] = Field(
+ None,
+ description='The mime type of the response. This is required if response_format is set.',
+ )
+ previous_interaction_id: Optional[str] = Field(
+ None, description='The ID of the previous interaction, if any.'
+ )
+ input: Union[str, List[Content], List[Turn], Content] = Field(
+ ..., description='The inputs for the interaction.'
+ )
+ generation_config: Optional[GenerationConfig] = Field(
+ None,
+ description='Input only. Configuration parameters for the model interaction.',
+ )
+
+
+class CreateAgentInteractionParams(BaseModel):
+ agent: AgentOption = Field(
+ ..., description='The name of the `Agent` used for generating the interaction.'
+ )
+ stream: Optional[bool] = Field(
+ None, description='Input only. Whether the interaction will be streamed.'
+ )
+ store: Optional[bool] = Field(
+ None,
+ description='Input only. Whether to store the response and request for later retrieval.',
+ )
+ id: Optional[str] = Field(
+ None,
+ description='Output only. A unique identifier for the interaction completion.',
+ )
+ status: Optional[Status3] = Field(
+ None, description='Output only. The status of the interaction.'
+ )
+ created: Optional[AwareDatetime] = Field(
+ None,
+ description='Output only. The time at which the response was created in ISO 8601 format\n(YYYY-MM-DDThh:mm:ssZ).',
+ )
+ updated: Optional[AwareDatetime] = Field(
+ None,
+ description='Output only. The time at which the response was last updated in ISO 8601 format\n(YYYY-MM-DDThh:mm:ssZ).',
+ )
+ role: Optional[str] = Field(
+ None, description='Output only. The role of the interaction.'
+ )
+ outputs: Optional[List[Content]] = Field(
+ None, description='Output only. Responses from the model.'
+ )
+ system_instruction: Optional[str] = Field(
+ None, description='System instruction for the interaction.'
+ )
+ tools: Optional[List[Tool]] = Field(
+ None,
+ description='A list of tool declarations the model may call during interaction.',
+ )
+ background: Optional[bool] = Field(
+ None, description='Whether to run the model interaction in the background.'
+ )
+ usage: Optional[Usage] = Field(
+ None,
+ description="Output only. Statistics on the interaction request's token usage.",
+ )
+ response_modalities: Optional[List[ResponseModality]] = Field(
+ None,
+ description='The requested modalities of the response (TEXT, IMAGE, AUDIO).',
+ )
+ response_format: Optional[Any] = Field(
+ None,
+ description='Enforces that the generated response is a JSON object that complies with\nthe JSON schema specified in this field.',
+ )
+ response_mime_type: Optional[str] = Field(
+ None,
+ description='The mime type of the response. This is required if response_format is set.',
+ )
+ previous_interaction_id: Optional[str] = Field(
+ None, description='The ID of the previous interaction, if any.'
+ )
+ input: Union[str, List[Content], List[Turn], Content] = Field(
+ ..., description='The inputs for the interaction.'
+ )
+ agent_config: Optional[Union[DynamicAgentConfig, DeepResearchAgentConfig]] = Field(
+ None, description='Configuration for the agent.', discriminator='type'
+ )
+
+
+class InteractionEvent(BaseModel):
+ event_type: Literal['interaction.start', 'interaction.complete']
+ interaction: Optional[Interaction] = None
+ event_id: Optional[str] = Field(
+ None,
+ description='The event_id token to be used to resume the interaction stream, from\nthis event.',
+ )
+
+
+class InteractionSseEvent(
+ RootModel[
+ Union[
+ InteractionEvent,
+ InteractionStatusUpdate,
+ ContentStart,
+ ContentDelta,
+ ContentStop,
+ ErrorEvent,
+ ]
+ ]
+):
+ root: Union[
+ InteractionEvent,
+ InteractionStatusUpdate,
+ ContentStart,
+ ContentDelta,
+ ContentStop,
+ ErrorEvent,
+ ] = Field(..., discriminator='event_type')
+
+
+# ============================================================
+# LiteLLM-specific types (added manually after generation)
+# ============================================================
+#
+# When regenerating this file, copy these types to the end.
+# See README.md for regeneration instructions.
+
+from pydantic import PrivateAttr
+
+from litellm.types.llms.base import BaseLiteLLMOpenAIResponseObject
+
+# Type alias for input
+InteractionInput = Union[str, Content, List[Content], List[Turn]]
+
+
+class InteractionsAPIResponse(BaseLiteLLMOpenAIResponseObject):
+ """
+ Response from the Interactions API.
+
+ Wraps the API response with LiteLLM-specific hidden params.
+ """
+ id: Optional[str] = None
+ object: Optional[str] = "interaction"
+ model: Optional[str] = None
+ agent: Optional[str] = None
+ status: Optional[str] = None
+ created: Optional[str] = None
+ updated: Optional[str] = None
+ role: Optional[str] = None
+ outputs: Optional[List[Dict[str, Any]]] = None
+ usage: Optional[Dict[str, Any]] = None
+
+ _hidden_params: dict = PrivateAttr(default_factory=dict)
+
+
+class InteractionsAPIStreamingResponse(BaseLiteLLMOpenAIResponseObject):
+ """
+ Streaming response chunk from the Interactions API.
+
+ Event types per OpenAPI spec:
+ - interaction.start, interaction.status_update, interaction.complete
+ - content.start, content.delta, content.stop
+ - error
+ """
+ event_type: Optional[str] = None
+ id: Optional[str] = None
+ object: Optional[str] = "interaction"
+ model: Optional[str] = None
+ agent: Optional[str] = None
+ status: Optional[str] = None
+ created: Optional[str] = None
+ updated: Optional[str] = None
+ role: Optional[str] = None
+ outputs: Optional[List[Dict[str, Any]]] = None
+ usage: Optional[Dict[str, Any]] = None
+ delta: Optional[Dict[str, Any]] = None
+
+ _hidden_params: dict = PrivateAttr(default_factory=dict)
+
+
+class DeleteInteractionResult(BaseLiteLLMOpenAIResponseObject):
+ """Result of deleting an interaction."""
+ success: bool = True
+ id: Optional[str] = None
+
+ _hidden_params: dict = PrivateAttr(default_factory=dict)
+
+
+class CancelInteractionResult(BaseLiteLLMOpenAIResponseObject):
+ """Result of cancelling an interaction."""
+ id: Optional[str] = None
+ status: Optional[str] = None
+
+ _hidden_params: dict = PrivateAttr(default_factory=dict)
+
+
+# Backwards compatibility aliases
+InteractionTool = Tool
+InteractionToolChoiceConfig = ToolChoiceConfig
+InteractionsAPIOptionalRequestParams = Dict[str, Any]
diff --git a/tests/test_litellm/interactions/test_google_interactions_integration.py b/tests/test_litellm/interactions/test_google_interactions_integration.py
new file mode 100644
index 00000000000..a2b255f315d
--- /dev/null
+++ b/tests/test_litellm/interactions/test_google_interactions_integration.py
@@ -0,0 +1,338 @@
+"""
+Integration tests for Google Interactions API.
+
+Tests the litellm.interactions.create() and related methods against the Google AI Studio API.
+
+Per OpenAPI spec: https://ai.google.dev/static/api/interactions.openapi.json
+
+Run with: pytest tests/test_litellm/interactions/test_google_interactions_integration.py -v
+"""
+
+import asyncio
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+import litellm
+import litellm.interactions as interactions
+
+# Test API key - should be set in environment
+GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
+
+
+def api_key():
+ """Fixture to provide the API key."""
+ if not GEMINI_API_KEY:
+ pytest.skip("GEMINI_API_KEY not set")
+ return GEMINI_API_KEY
+
+
+class TestGoogleInteractionsCreate:
+ """Tests for creating interactions via litellm.interactions.create()."""
+
+ def test_create_simple_string_input(self, api_key):
+ """Test creating an interaction with a simple string input."""
+ response = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input="Hello, what is 2 + 2?",
+ api_key=api_key,
+ )
+ print("SIMPLE RESPONSE: ", response)
+ assert response is not None
+ assert response.id is not None or response.status is not None
+
+ # Check outputs per OpenAPI spec
+ if response.outputs:
+ assert len(response.outputs) > 0
+ print(f"Response outputs: {response.outputs}")
+
+ # Check usage per OpenAPI spec
+ if response.usage:
+ print(f"Usage: {response.usage}")
+
+ def test_create_with_content_list(self, api_key):
+ """Test creating an interaction with a structured content list (Turn format)."""
+ response = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input=[
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": "What is the capital of France?"}]
+ }
+ ],
+ api_key=api_key,
+ )
+
+ assert response is not None
+ print(f"Response: {response}")
+
+ def test_create_with_system_instruction(self, api_key):
+ """Test creating an interaction with system_instruction (per OpenAPI spec)."""
+ response = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input="What are you?",
+ system_instruction="You are a helpful pirate assistant. Always respond like a pirate.",
+ api_key=api_key,
+ )
+
+ assert response is not None
+ print(f"Response with system_instruction: {response}")
+
+ def test_create_with_tools(self, api_key):
+ """Test creating an interaction with tools (per OpenAPI spec)."""
+ response = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input="What's the weather in Boston?",
+ tools=[
+ {
+ "type": "function",
+ "name": "get_weather",
+ "description": "Get the weather for a location",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "location": {"type": "string", "description": "The city name"}
+ },
+ "required": ["location"]
+ }
+ }
+ ],
+ api_key=api_key,
+ )
+
+ assert response is not None
+ # Check if status is requires_action (function call)
+ print(f"Response status: {response.status}")
+ print(f"Response outputs: {response.outputs}")
+
+ @pytest.mark.asyncio
+ async def test_acreate_simple(self, api_key):
+ """Test async interaction creation."""
+ response = await interactions.acreate(
+ model="gemini/gemini-2.5-flash",
+ input="What is the speed of light?",
+ api_key=api_key,
+ )
+
+ assert response is not None
+ print(f"Async response: {response}")
+
+
+class TestGoogleInteractionsStreaming:
+ """Tests for streaming interactions."""
+
+ def test_create_streaming(self, api_key):
+ """Test creating a streaming interaction."""
+ response_stream = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input="Count from 1 to 5 slowly.",
+ stream=True,
+ api_key=api_key,
+ )
+
+ # Collect all chunks
+ chunks = []
+ for chunk in response_stream:
+ chunks.append(chunk)
+ print(f"Streaming chunk: {chunk}")
+
+ assert len(chunks) > 0
+ print(f"Total chunks received: {len(chunks)}")
+
+ @pytest.mark.asyncio
+ async def test_acreate_streaming(self, api_key):
+ """Test async streaming interaction."""
+ response_stream = await interactions.acreate(
+ model="gemini/gemini-2.5-flash",
+ input="Count from 1 to 3.",
+ stream=True,
+ api_key=api_key,
+ )
+
+ # Collect all chunks
+ chunks = []
+ async for chunk in response_stream:
+ chunks.append(chunk)
+ print(f"Async streaming chunk: {chunk}")
+
+ assert len(chunks) > 0
+ print(f"Total async chunks received: {len(chunks)}")
+
+
+class TestGoogleInteractionsMultiTurn:
+ """Tests for multi-turn conversations using Turn[] input."""
+
+ def test_multi_turn_conversation(self, api_key):
+ """Test a multi-turn conversation per OpenAPI spec (Turn[] format)."""
+ response = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input=[
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": "My name is Alice."}]
+ },
+ {
+ "role": "model",
+ "content": [{"type": "text", "text": "Hello Alice! Nice to meet you."}]
+ },
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": "What is my name?"}]
+ }
+ ],
+ api_key=api_key,
+ )
+
+ assert response is not None
+ print(f"Multi-turn response: {response}")
+
+
+class TestGoogleInteractionsAgent:
+ """Tests for agent interactions (per OpenAPI spec)."""
+
+ @pytest.mark.skip(reason="Deep research agent may not be available in all accounts")
+ def test_create_agent_interaction(self, api_key):
+ """Test creating an agent interaction per OpenAPI spec."""
+ response = interactions.create(
+ agent="deep-research-pro-preview-12-2025",
+ input="Research the current state of quantum computing",
+ api_key=api_key,
+ )
+
+ assert response is not None
+ print(f"Agent response: {response}")
+
+
+class TestGoogleInteractionsGetDelete:
+ """Tests for get and delete operations."""
+
+ @pytest.mark.skip(reason="Get/Delete require valid interaction IDs from previous calls")
+ def test_get_interaction(self, api_key):
+ """Test getting an interaction by ID."""
+ # First create an interaction
+ create_response = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input="Hello",
+ api_key=api_key,
+ )
+
+ if create_response.id:
+ # Then get it
+ get_response = interactions.get(
+ interaction_id=create_response.id,
+ api_key=api_key,
+ )
+ assert get_response is not None
+ print(f"Get response: {get_response}")
+
+ @pytest.mark.skip(reason="Get/Delete require valid interaction IDs from previous calls")
+ def test_delete_interaction(self, api_key):
+ """Test deleting an interaction by ID."""
+ # First create an interaction
+ create_response = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input="Hello",
+ api_key=api_key,
+ )
+
+ if create_response.id:
+ # Then delete it
+ delete_result = interactions.delete(
+ interaction_id=create_response.id,
+ api_key=api_key,
+ )
+ assert delete_result.success is True
+ print(f"Delete result: {delete_result}")
+
+
+class TestGoogleInteractionsErrorHandling:
+ """Tests for error handling."""
+
+ def test_invalid_model(self, api_key):
+ """Test error handling for invalid model."""
+ with pytest.raises(Exception):
+ interactions.create(
+ model="gemini/invalid-model-name-xyz",
+ input="Hello",
+ api_key=api_key,
+ )
+
+ def test_missing_model_and_agent(self, api_key):
+ """Test error when neither model nor agent is provided."""
+ with pytest.raises(Exception): # Can be ValueError or APIConnectionError
+ interactions.create(
+ input="Hello",
+ api_key=api_key,
+ )
+
+
+class TestGoogleInteractionsResponseStructure:
+ """Tests to verify the response structure matches OpenAPI spec."""
+
+ def test_response_has_expected_fields(self, api_key):
+ """Test that the response has fields per OpenAPI spec."""
+ response = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input="Hello",
+ api_key=api_key,
+ )
+
+ # Check fields per OpenAPI spec
+ assert hasattr(response, 'id')
+ assert hasattr(response, 'object')
+ assert hasattr(response, 'status')
+ assert hasattr(response, 'outputs')
+ assert hasattr(response, 'usage')
+ assert hasattr(response, 'model') or hasattr(response, 'agent')
+ assert hasattr(response, 'role')
+ assert hasattr(response, 'created')
+ assert hasattr(response, 'updated')
+
+ print(f"Response structure: id={response.id}, status={response.status}, object={response.object}")
+
+
+if __name__ == "__main__":
+ # Run a quick smoke test
+ print("Running Google Interactions API smoke test...")
+
+ api_key = GEMINI_API_KEY
+ if not api_key:
+ print("GEMINI_API_KEY not set, skipping smoke test")
+ exit(1)
+
+ print("\n1. Testing basic interaction...")
+ response = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input="What is 2 + 2?",
+ api_key=api_key,
+ )
+ print(f"Response: {response}")
+
+ print("\n2. Testing streaming interaction...")
+ stream = interactions.create(
+ model="gemini/gemini-2.5-flash",
+ input="Count to 3.",
+ stream=True,
+ api_key=api_key,
+ )
+ print("Streaming response chunks:")
+ for chunk in stream:
+ print(f" {chunk}")
+
+ print("\n3. Testing async interaction...")
+ async def test_async():
+ response = await interactions.acreate(
+ model="gemini/gemini-2.5-flash",
+ input="Say hello!",
+ api_key=api_key,
+ )
+ return response
+
+ async_response = asyncio.run(test_async())
+ print(f"Async response: {async_response}")
+
+ print("\nSmoke test complete!")
diff --git a/tests/test_litellm/interactions/test_openapi_compliance.py b/tests/test_litellm/interactions/test_openapi_compliance.py
new file mode 100644
index 00000000000..d18d52f96be
--- /dev/null
+++ b/tests/test_litellm/interactions/test_openapi_compliance.py
@@ -0,0 +1,237 @@
+"""
+OpenAPI compliance tests for Google Interactions API.
+
+Validates that our SDK requests/responses match the OpenAPI spec at:
+https://ai.google.dev/static/api/interactions.openapi.json
+
+Run with: pytest tests/test_litellm/interactions/test_openapi_compliance.py -v
+"""
+
+import json
+import os
+from typing import Any, Dict
+from unittest.mock import MagicMock, patch
+
+import httpx
+import pytest
+from openapi_core import OpenAPI
+from openapi_core.testing.mock import MockRequest, MockResponse
+
+OPENAPI_SPEC_URL = "https://ai.google.dev/static/api/interactions.openapi.json"
+
+
[email protected](scope="module")
+def openapi_spec():
+ """Load the OpenAPI spec."""
+ response = httpx.get(OPENAPI_SPEC_URL)
+ response.raise_for_status()
+ spec_dict = response.json()
+ return OpenAPI.from_dict(spec_dict)
+
+
[email protected](scope="module")
+def spec_dict():
+ """Load raw spec dict for manual validation."""
+ response = httpx.get(OPENAPI_SPEC_URL)
+ response.raise_for_status()
+ return response.json()
+
+
+class TestRequestCompliance:
+ """Tests that our request bodies match the OpenAPI spec."""
+
+ def test_create_model_interaction_request_schema(self, spec_dict):
+ """Verify CreateModelInteractionParams schema fields."""
+ schema = spec_dict["components"]["schemas"]["CreateModelInteractionParams"]
+
+ # Required fields per spec
+ assert "model" in schema["required"]
+ assert "input" in schema["required"]
+
+ # Check our supported optional fields exist in spec
+ our_optional_fields = [
+ "tools", "system_instruction", "generation_config",
+ "stream", "store", "background", "response_modalities",
+ "response_format", "response_mime_type", "previous_interaction_id"
+ ]
+
+ spec_properties = schema["properties"]
+ for field in our_optional_fields:
+ assert field in spec_properties, f"Field '{field}' not in OpenAPI spec"
+ print(f"✓ Field '{field}' exists in spec")
+
+ def test_input_types_match_spec(self, spec_dict):
+ """Verify input field supports string, Content, Content[], Turn[]."""
+ schema = spec_dict["components"]["schemas"]["CreateModelInteractionParams"]
+ input_schema = schema["properties"]["input"]
+
+ # Should be oneOf with multiple types
+ assert "oneOf" in input_schema
+
+ input_types = []
+ for option in input_schema["oneOf"]:
+ if option.get("type") == "string":
+ input_types.append("string")
+ elif option.get("type") == "array":
+ input_types.append("array")
+ elif "$ref" in option:
+ input_types.append(option["$ref"])
+
+ print(f"Input supports types: {input_types}")
+ assert "string" in input_types, "Input should support string"
+ assert "array" in input_types, "Input should support array"
+
+ def test_content_schema_uses_discriminator(self, spec_dict):
+ """Verify Content uses type discriminator."""
+ content_schema = spec_dict["components"]["schemas"]["Content"]
+
+ assert "discriminator" in content_schema
+ assert content_schema["discriminator"]["propertyName"] == "type"
+
+ # Check TextContent is an option
+ mapping = content_schema["discriminator"]["mapping"]
+ assert "text" in mapping
+ print(f"Content type discriminator mapping: {list(mapping.keys())}")
+
+ def test_text_content_schema(self, spec_dict):
+ """Verify TextContent schema."""
+ text_schema = spec_dict["components"]["schemas"]["TextContent"]
+
+ assert "type" in text_schema["required"]
+ assert "text" in text_schema["properties"]
+ assert text_schema["properties"]["type"].get("const") == "text"
+ print("✓ TextContent schema is correct")
+
+ def test_turn_schema(self, spec_dict):
+ """Verify Turn schema for multi-turn conversations."""
+ turn_schema = spec_dict["components"]["schemas"]["Turn"]
+
+ assert "role" in turn_schema["properties"]
+ assert "content" in turn_schema["properties"]
+
+ # Content can be string or Content[]
+ content_prop = turn_schema["properties"]["content"]
+ assert "oneOf" in content_prop
+ print("✓ Turn schema supports role + content")
+
+
+class TestResponseCompliance:
+ """Tests that our response types match the OpenAPI spec."""
+
+ def test_interaction_response_fields(self, spec_dict):
+ """Verify our InteractionsAPIResponse has correct fields."""
+ # The response is the Interaction schema
+ # Check CreateModelInteractionParams which includes output fields
+ schema = spec_dict["components"]["schemas"]["CreateModelInteractionParams"]
+
+ # Output fields (readOnly)
+ output_fields = ["id", "status", "created", "updated", "role", "outputs", "usage"]
+
+ for field in output_fields:
+ assert field in schema["properties"], f"Output field '{field}' not in spec"
+ print(f"✓ Output field '{field}' exists in spec")
+
+ def test_status_enum_values(self, spec_dict):
+ """Verify status enum values match spec."""
+ schema = spec_dict["components"]["schemas"]["CreateModelInteractionParams"]
+ status_prop = schema["properties"]["status"]
+
+ expected_statuses = ["UNSPECIFIED", "IN_PROGRESS", "REQUIRES_ACTION", "COMPLETED", "FAILED", "CANCELLED"]
+ assert status_prop["enum"] == expected_statuses
+ print(f"✓ Status enum values: {expected_statuses}")
+
+ def test_usage_schema(self, spec_dict):
+ """Verify Usage schema fields."""
+ usage_schema = spec_dict["components"]["schemas"]["Usage"]
+
+ # Key usage fields
+ expected_fields = ["total_input_tokens", "total_output_tokens", "total_tokens"]
+
+ for field in expected_fields:
+ assert field in usage_schema["properties"], f"Usage field '{field}' not in spec"
+ print(f"✓ Usage field '{field}' exists")
+
+
+class TestToolsCompliance:
+ """Tests that our tool types match the OpenAPI spec."""
+
+ def test_tool_schema(self, spec_dict):
+ """Verify Tool schema."""
+ tool_schema = spec_dict["components"]["schemas"]["Tool"]
+
+ # Tool should be oneOf multiple tool types
+ assert "oneOf" in tool_schema or "properties" in tool_schema
+ print(f"✓ Tool schema found")
+
+ def test_function_declaration_schema(self, spec_dict):
+ """Verify FunctionDeclaration schema for function tools."""
+ if "FunctionDeclaration" in spec_dict["components"]["schemas"]:
+ func_schema = spec_dict["components"]["schemas"]["FunctionDeclaration"]
+ assert "name" in func_schema.get("properties", {}) or "name" in func_schema.get("required", [])
+ print("✓ FunctionDeclaration schema found")
+ else:
+ print("⚠ FunctionDeclaration schema not found (may be nested)")
+
+
+class TestEndpointCompliance:
+ """Tests that our endpoints match the OpenAPI spec."""
+
+ def test_create_endpoint_exists(self, spec_dict):
+ """Verify POST /interactions endpoint exists."""
+ paths = spec_dict["paths"]
+
+ # Find the create interactions endpoint
+ create_path = None
+ for path, methods in paths.items():
+ if "interactions" in path and "post" in methods:
+ create_path = path
+ break
+
+ assert create_path is not None, "POST /interactions endpoint not found"
+ print(f"✓ Create endpoint: POST {create_path}")
+
+ def test_get_endpoint_exists(self, spec_dict):
+ """Verify GET /interactions/{id} endpoint exists."""
+ paths = spec_dict["paths"]
+
+ get_path = None
+ for path, methods in paths.items():
+ if "{id}" in path and "interactions" in path and "get" in methods:
+ get_path = path
+ break
+
+ assert get_path is not None, "GET /interactions/{id} endpoint not found"
+ print(f"✓ Get endpoint: GET {get_path}")
+
+ def test_delete_endpoint_exists(self, spec_dict):
+ """Verify DELETE /interactions/{id} endpoint exists."""
+ paths = spec_dict["paths"]
+
+ delete_path = None
+ for path, methods in paths.items():
+ if "{id}" in path and "interactions" in path and "delete" in methods:
+ delete_path = path
+ break
+
+ assert delete_path is not None, "DELETE /interactions/{id} endpoint not found"
+ print(f"✓ Delete endpoint: DELETE {delete_path}")
+
+
+if __name__ == "__main__":
+ # Quick manual test
+ import httpx
+
+ print("Loading OpenAPI spec...")
+ response = httpx.get(OPENAPI_SPEC_URL)
+ spec = response.json()
+
+ print(f"\nSpec version: {spec.get('openapi')}")
+ print(f"API title: {spec.get('info', {}).get('title')}")
+ print(f"\nEndpoints:")
+ for path, methods in spec.get("paths", {}).items():
+ for method in methods:
+ if method in ["get", "post", "delete", "put", "patch"]:
+ print(f" {method.upper()} {path}")
+
+ print(f"\nSchemas: {list(spec.get('components', {}).get('schemas', {}).keys())[:10]}...")
+