diff --git a/src/google/adk/models/lite_llm.py b/src/google/adk/models/lite_llm.py index 7300fab9ca7..cac758a4ed5 100644 --- a/src/google/adk/models/lite_llm.py +++ b/src/google/adk/models/lite_llm.py @@ -50,6 +50,7 @@ from pydantic import BaseModel from pydantic import Field from pydantic import PrivateAttr +from pydantic_core import to_jsonable_python from typing_extensions import NotRequired from typing_extensions import override from typing_extensions import Required @@ -1336,6 +1337,14 @@ def completion( def _safe_json_serialize(obj: object) -> str: """Convert any Python object to a JSON-serializable type or string. + Tool results can hold values the json module cannot encode, such as dates, + Decimals, enums, UUIDs or Pydantic models. An AgentTool wrapping an agent + with an output_schema returns these, since the schema is dumped in Python + mode. They are converted the way the Gemini and Gemma paths convert a + function response, so the model still gets JSON instead of the Python repr + of the whole payload. Only a payload that Pydantic cannot serialize either + falls back to str(). + Args: obj: The object to serialize. @@ -1346,6 +1355,13 @@ def _safe_json_serialize(obj: object) -> str: try: # Try direct JSON serialization first return json.dumps(obj, ensure_ascii=False) + except (TypeError, ValueError, OverflowError, RecursionError): + pass + try: + jsonable = to_jsonable_python( + obj, by_alias=False, exclude_none=True, bytes_mode="base64" + ) + return json.dumps(jsonable, ensure_ascii=False) except (TypeError, ValueError, OverflowError, RecursionError): return str(obj) diff --git a/tests/unittests/models/test_litellm.py b/tests/unittests/models/test_litellm.py index af993c02fb2..f7790ffceaf 100644 --- a/tests/unittests/models/test_litellm.py +++ b/tests/unittests/models/test_litellm.py @@ -14,6 +14,9 @@ import base64 import contextlib +import datetime +import decimal +import enum import json import logging import os @@ -25,6 +28,7 @@ from unittest.mock import MagicMock from unittest.mock import Mock from unittest.mock import patch +import uuid import warnings from google.adk.agents.context_cache_config import ContextCacheConfig @@ -1238,6 +1242,93 @@ def test_safe_json_serialize_recursion_error_falls_back_to_str(): assert _safe_json_serialize({"a": 1}) == str({"a": 1}) +class _InvoiceStatus(enum.Enum): + PAID = "paid" + + +class _InvoiceLine(BaseModel): + sku: str + note: str | None = None + + +class _Invoice(BaseModel): + due_date: datetime.date + total: decimal.Decimal + status: _InvoiceStatus + + +def test_safe_json_serialize_encodes_values_json_module_cannot(): + payload = { + "due_date": datetime.date(2026, 12, 1), + "issued_at": datetime.datetime(2026, 11, 1, 9, 30), + "total": decimal.Decimal("12.50"), + "status": _InvoiceStatus.PAID, + "id": uuid.UUID("12345678-1234-5678-1234-567812345678"), + "tags": {"urgent"}, + "blob": b"hi", + "lines": [_InvoiceLine(sku="A-1")], + "missing": None, + } + + assert json.loads(_safe_json_serialize(payload)) == { + "due_date": "2026-12-01", + "issued_at": "2026-11-01T09:30:00", + "total": "12.50", + "status": "paid", + "id": "12345678-1234-5678-1234-567812345678", + "tags": ["urgent"], + "blob": "aGk=", + "lines": [{"sku": "A-1"}], + "missing": None, + } + + +def test_safe_json_serialize_keeps_non_ascii_text_in_converted_payload(): + serialized = _safe_json_serialize( + {"city": "Zürich", "on": datetime.date(2026, 12, 1)} + ) + + assert serialized == '{"city": "Zürich", "on": "2026-12-01"}' + + +def test_safe_json_serialize_unknown_nested_value_falls_back_to_str(): + class _NotJsonable: + + def __repr__(self): + return "" + + payload = {"value": _NotJsonable()} + + assert _safe_json_serialize(payload) == str(payload) + + +@pytest.mark.asyncio +async def test_content_to_message_param_output_schema_tool_result_is_json(): + # An AgentTool wrapping an agent with an output_schema returns the schema + # dumped in Python mode, so dates, Decimals and enums reach the tool result. + response = _Invoice( + due_date=datetime.date(2026, 12, 1), + total=decimal.Decimal("12.50"), + status=_InvoiceStatus.PAID, + ).model_dump() + part = types.Part.from_function_response( + name="extract_invoice", response=response + ) + part.function_response.id = "tool_call_1" + + message = await _content_to_message_param( + types.Content(role="user", parts=[part]) + ) + + assert message["role"] == "tool" + assert message["tool_call_id"] == "tool_call_1" + assert json.loads(message["content"]) == { + "due_date": "2026-12-01", + "total": "12.50", + "status": "paid", + } + + MULTIPLE_FUNCTION_CALLS_STREAM = [ ModelResponseStream( choices=[