adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Non-serializable FunctionTool objects in state_delta cause PydanticSerializationError in AG-UI integration

Open surfai opened this issue 8 months ago • 6 comments

Description

When using ADK with ag_ui_adk, the event encoder fails with PydanticSerializationError because state_delta events contain FunctionTool objects that Pydantic cannot serialize to JSON.

The AG-UI event encoder calls event.model_dump_json() on StateDeltaEvent, which includes state_delta values. ADK injects internal objects (e.g. FunctionTool instances) into the session state, and these end up in state_delta patches sent to the frontend.

Error

Event encoding failed: Unable to serialize unknown type: <class 'google.adk.tools.function_tool.FunctionTool'>

Steps to Reproduce

from google.adk.agents import LlmAgent
from ag_ui_adk import ADKAgent, add_adk_fastapi_endpoint

agent = LlmAgent(
    name="my_agent",
    model="gemini-2.5-flash",
    instruction="You are helpful.",
    tools=[my_function_tool],
)

adk_agent = ADKAgent(
    adk_agent=agent,
    app_name="demo",
    user_id="user1",
    use_in_memory_services=True,
)

# Send any message — the state_delta event will contain FunctionTool references

Expected Behavior

state_delta events should only contain JSON-serializable values. Internal ADK objects should be filtered out before emitting state events.

Workaround

Filter non-serializable values from state_delta before creating the event:

import json
from ag_ui_adk.event_translator import EventTranslator

def _is_json_serializable(value):
    try:
        json.dumps(value)
        return True
    except (TypeError, ValueError, OverflowError):
        return False

_orig = EventTranslator._create_state_delta_event

def _patched(self, state_delta, thread_id, run_id):
    filtered = {k: v for k, v in state_delta.items() if _is_json_serializable(v)}
    return _orig(self, filtered, thread_id, run_id)

EventTranslator._create_state_delta_event = _patched

Related

  • #3288 (similar serialization issue with SecuritySchemeType)

Environment

  • google-adk==2.0.0a2
  • ag-ui-adk==0.5.1
  • Python 3.14
  • macOS

Note: This issue was identified with AI assistance (Claude Code).

surfai avatar Mar 29 '26 04:03 surfai

Hello @surfai ,

Could you please confirm the type of state_delta you are receiving? I attempted to reproduce this issue, and it appears all state_delta values are of the list type. Also, could you please share the step-by-step reproduction steps to help me investigate this further? Any additional analysis or details you could share would be helpful.

llalitkumarrr avatar Apr 01 '26 10:04 llalitkumarrr

Hi @llalitkumarrr — thanks for taking the time to look into this, really appreciate it.

First off, we're really enjoying ADK 2.0 — the Workflow graph and the new event model give a lot more flexibility compared to 1.x. Great work on that.

Full transparency: we actually moved away from ag_ui_adk yesterday and switched to direct SSE streaming instead. As a third-party adapter (not part of ADK proper), and with ADK still at alpha 2, we felt more comfortable owning the transport layer ourselves. But it's still a valid bug that'll bite anyone using ag_ui_adk with Workflow agents that have tools.

state_delta type: It's a Dict[str, Any]. The problem is the values — specifically state_delta['temp:tools_dict'] contains a dict[str, FunctionTool], and FunctionTool is not JSON-serializable.

Where it comes from: ADK's _call_llm_node.py (~line 126) stores the resolved tools dict in temp state:

ctx.state['temp:tools_dict'] = llm_request.tools_dict

The session service has _trim_temp_delta_state() to strip temp: keys before persistence, but any consumer that processes the event before trimming sees the raw state_delta with FunctionTool objects in it.

Minimal reproduction (google-adk==2.0.0a2, ag_ui_adk==0.1.0, pydantic==2.12.5):

from google.adk.tools import FunctionTool
from ag_ui_adk.event_translator import EventTranslator

def greet(name: str) -> str:
    """Say hello."""
    return f"Hello, {name}!"

ft = FunctionTool(greet)

# Simulates what _call_llm_node puts in state_delta
state_delta = {
    "user_request": "hello",
    "temp:tools_dict": {"greet": ft},  # FunctionTool — not serializable
}

translator = EventTranslator()
event = translator._create_state_delta_event(state_delta, "thread", "run")
event.model_dump_json()  # PydanticSerializationError

Error:

pydantic_core._pydantic_core.PydanticSerializationError: 
  Unable to serialize unknown type: <class 'google.adk.tools.function_tool.FunctionTool'>

To trigger via actual agent execution: Use a Workflow with at least one Agent node that has tools, served through ag_ui_adk's add_adk_fastapi_endpoint. Send any message. The first LLM call stores temp:tools_dict in state, and the EventTranslator crashes trying to serialize the resulting state_delta into SSE.

Our workaround (before we switched to direct SSE): We wrapped EventTranslator._create_state_delta_event to filter out values that fail json.dumps() before they reach Pydantic serialization.

surfai avatar Apr 01 '26 23:04 surfai

Update: This same serialization failure also occurs in ADK's own adk_web_server.py event generator (not just ag_ui_adk).

When the request body includes streaming: true (which @assistant-ui/react-google-adk sends by default), the PROGRESSIVE_SSE_STREAMING feature activates and event_to_stream.model_dump_json() at adk_web_server.py:1853 hits the same FunctionTool serialization error:

ERROR - adk_web_server.py:1853 - Error in event_generator: Unable to serialize unknown type: <class 'google.adk.tools.function_tool.FunctionTool'>
pydantic_core._pydantic_core.PydanticSerializationError: Unable to serialize unknown type: <class 'google.adk.tools.function_tool.FunctionTool'>

This kills the SSE stream mid-flight and the client hangs.

Impact: Affects anyone using adk api_server with a frontend that sends streaming: true — not limited to ag_ui_adk. The @assistant-ui/react-google-adk client hardcodes streaming: true in the request body (AdkClient.js:33), so all assistant-ui users hit this.

Current workaround: Proxy that strips or overrides streaming from the request body before it reaches ADK.

Environment: google-adk==2.0.0a2, Python 3.14, macOS

surfai avatar Apr 07 '26 02:04 surfai

Root cause trace

Dug into the 2.0.0a2 source. The bug is a timing gap — temp: keys are filtered before persistence but not before SSE serialization.

The chain

  1. _call_llm_node.py:131 stores non-serializable FunctionTool objects in temp state:

    ctx.state['temp:tools_dict'] = llm_request.tools_dict
    
  2. context.py:188 — State.delta is a reference to event_actions.state_delta:

    self._state = State(
        value=invocation_context.session.state,
        delta=self._event_actions.state_delta,  # same dict object
    )
    

    So writing ctx.state['temp:tools_dict'] = ... immediately mutates event_actions.state_delta.

  3. base_session_service.py:113 — _trim_temp_delta_state() filters temp: keys, but only inside append_event():

    event = self._trim_temp_delta_state(event)
    
  4. adk_web_server.py:1844 — the SSE generator serializes events before they reach append_event():

    sse_event = event_to_stream.model_dump_json(
        exclude_none=True, by_alias=True,
    )
    

    → state_delta still contains {'temp:tools_dict': {name: FunctionTool(...)}} → 💥

Why non-streaming works

When streaming=false, events are buffered through the full append_event() pipeline (which calls _trim_temp_delta_state), then serialized in the /run response. The temp keys are gone by serialization time.

Proposed fix

The cleanest fix is to apply the same temp: key filtering in the SSE generator before serialization. In adk_web_server.py, before line 1844:

for event_to_stream in events_to_stream:
    # Filter temp state before SSE serialization (same as
    # _trim_temp_delta_state in base_session_service.py)
    if (event_to_stream.actions
        and event_to_stream.actions.state_delta):
        event_to_stream.actions.state_delta = {
            k: v for k, v in event_to_stream.actions.state_delta.items()
            if not k.startswith("temp:")
        }
    sse_event = event_to_stream.model_dump_json(
        exclude_none=True,
        by_alias=True,
    )

Alternatively, the filtering could be pushed deeper — into State.__setitem__ or the event emission path in _function_node.py — so that temp: keys never reach state_delta in the first place. But that would change the semantics for append_event() which currently relies on seeing them (to apply temp state to the in-memory session before trimming).

A more structural approach would be to give State a separate _temp_delta dict that doesn't flow into event_actions.state_delta at all, but that's a bigger refactor.

Happy to submit a PR for whichever approach you prefer.

surfai avatar Apr 07 '26 02:04 surfai

Here's the proposed fix as a diff against adk_web_server.py. Applies temp: key filtering in the SSE generator before serialization — mirrors what _trim_temp_delta_state() already does in base_session_service.py:131-146 for persistence.

--- a/src/google/adk/cli/adk_web_server.py
+++ b/src/google/adk/cli/adk_web_server.py
@@ -1841,6 +1841,14 @@ class ADKWebServer:
                 events_to_stream = [content_event, artifact_event]
 
               for event_to_stream in events_to_stream:
+                # Filter temp-scoped state keys before SSE serialization.
+                # Temp state (prefix "temp:") can contain non-serializable
+                # objects (e.g. FunctionTool instances stored by
+                # _call_llm_node). _trim_temp_delta_state() handles this
+                # for persistence in append_event(), but SSE events are
+                # serialized before reaching that path.
+                if event_to_stream.actions and event_to_stream.actions.state_delta:
+                  event_to_stream.actions.state_delta = {
+                      k: v for k, v in event_to_stream.actions.state_delta.items()
+                      if not k.startswith("temp:")
+                  }
                 sse_event = event_to_stream.model_dump_json(
                     exclude_none=True,
                     by_alias=True,

surfai avatar Apr 07 '26 02:04 surfai

closing in favor of #5026

sasha-gitg avatar Apr 10 '26 23:04 sasha-gitg