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

TypeError: Object of type bytes is not JSON serializable [adk web --session_db_url 'postgresql://xxx:[email protected]:5432/xxx']

Open TTWShell opened this issue 1 year ago • 8 comments

Running adk web --session_db_url resulted in a database write error for event_generator

2025-06-03 16:07:27,050 - ERROR - fast_api.py:708 - Error in event_generator: (builtins.TypeError) Object of type bytes is not JSON serializable
[SQL: INSERT INTO events (id, app_name, user_id, session_id, invocation_id, author, branch, timestamp, content, actions, long_running_tool_ids_json, grounding_metadata, partial, turn_complete, error_code, error_message, interrupted) VALUES (%(id)s, %(app_name)s, %(user_id)s, %(session_id)s, %(invocation_id)s, %(author)s, %(branch)s, %(timestamp)s, %(content)s::JSONB, %(actions)s, %(long_running_tool_ids_json)s, %(grounding_metadata)s::JSONB, %(partial)s, %(turn_complete)s, %(error_code)s, %(error_message)s, %(interrupted)s)]
[parameters: [{'author': 'Coordinator', 'user_id': 'user', 'app_name': 'bi_agent', 'timestamp': datetime.datetime(2025, 6, 3, 16, 7, 25, 454928), 'long_running_tool ... (1456 characters truncated) ... ', 'turn_complete': None, 'branch': None, 'interrupted': None, 'partial': None, 'grounding_metadata': None, 'error_message': None, 'error_code': None}]]
Traceback (most recent call last):
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1811, in _execute_context
    context = constructor(
        dialect, self, conn, execution_options, *args, **kw
    )
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/engine/default.py", line 1519, in _init_compiled
    flattened_processors[key](compiled_params[key])
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/sql/type_api.py", line 2096, in process
    return fixed_impl_processor(
        fixed_process_param(value, dialect)
    )
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/sql/sqltypes.py", line 2792, in process
    return json_serializer(value)
  File "/Users/apple/.local/share/uv/python/cpython-3.13.3-macos-x86_64-none/lib/python3.13/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^^^
  File "/Users/apple/.local/share/uv/python/cpython-3.13.3-macos-x86_64-none/lib/python3.13/json/encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Users/apple/.local/share/uv/python/cpython-3.13.3-macos-x86_64-none/lib/python3.13/json/encoder.py", line 261, in iterencode
    return _iterencode(o, 0)
  File "/Users/apple/.local/share/uv/python/cpython-3.13.3-macos-x86_64-none/lib/python3.13/json/encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
                    f'is not JSON serializable')
TypeError: Object of type bytes is not JSON serializable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/google/adk/cli/fast_api.py", line 697, in event_generator
    async for event in runner.run_async(
    ...<8 lines>...
      yield f"data: {sse_event}\n\n"
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/google/adk/runners.py", line 199, in run_async
    await self.session_service.append_event(session=session, event=event)
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/google/adk/sessions/database_session_service.py", line 548, in append_event
    session_factory.commit()
    ~~~~~~~~~~~~~~~~~~~~~~^^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/session.py", line 2032, in commit
    trans.commit(_to_root=True)
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^
  File "<string>", line 2, in commit
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/state_changes.py", line 139, in _go
    ret_value = fn(self, *arg, **kw)
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/session.py", line 1313, in commit
    self._prepare_impl()
    ~~~~~~~~~~~~~~~~~~^^
  File "<string>", line 2, in _prepare_impl
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/state_changes.py", line 139, in _go
    ret_value = fn(self, *arg, **kw)
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/session.py", line 1288, in _prepare_impl
    self.session.flush()
    ~~~~~~~~~~~~~~~~~~^^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/session.py", line 4345, in flush
    self._flush(objects)
    ~~~~~~~~~~~^^^^^^^^^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/session.py", line 4480, in _flush
    with util.safe_reraise():
         ~~~~~~~~~~~~~~~~~^^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/util/langhelpers.py", line 224, in __exit__
    raise exc_value.with_traceback(exc_tb)
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/session.py", line 4441, in _flush
    flush_context.execute()
    ~~~~~~~~~~~~~~~~~~~~~^^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/unitofwork.py", line 466, in execute
    rec.execute(self)
    ~~~~~~~~~~~^^^^^^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/unitofwork.py", line 642, in execute
    util.preloaded.orm_persistence.save_obj(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        self.mapper,
        ^^^^^^^^^^^^
        uow.states_for_mapper_hierarchy(self.mapper, False, False),
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        uow,
        ^^^^
    )
    ^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/persistence.py", line 93, in save_obj
    _emit_insert_statements(
    ~~~~~~~~~~~~~~~~~~~~~~~^
        base_mapper,
        ^^^^^^^^^^^^
    ...<3 lines>...
        insert,
        ^^^^^^^
    )
    ^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/orm/persistence.py", line 1048, in _emit_insert_statements
    result = connection.execute(
        statement, multiparams, execution_options=execution_options
    )
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1415, in execute
    return meth(
        self,
        distilled_parameters,
        execution_options or NO_OPTIONS,
    )
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/sql/elements.py", line 523, in _execute_on_connection
    return connection._execute_clauseelement(
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        self, distilled_params, execution_options
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1637, in _execute_clauseelement
    ret = self._execute_context(
        dialect,
    ...<8 lines>...
        cache_hit=cache_hit,
    )
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1817, in _execute_context
    self._handle_dbapi_exception(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        e, str(statement), parameters, None, None
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 2351, in _handle_dbapi_exception
    raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1811, in _execute_context
    context = constructor(
        dialect, self, conn, execution_options, *args, **kw
    )
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/engine/default.py", line 1519, in _init_compiled
    flattened_processors[key](compiled_params[key])
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/sql/type_api.py", line 2096, in process
    return fixed_impl_processor(
        fixed_process_param(value, dialect)
    )
  File "/Users/apple/workspace/bi_agent/.venv/lib/python3.13/site-packages/sqlalchemy/sql/sqltypes.py", line 2792, in process
    return json_serializer(value)
  File "/Users/apple/.local/share/uv/python/cpython-3.13.3-macos-x86_64-none/lib/python3.13/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^^^
  File "/Users/apple/.local/share/uv/python/cpython-3.13.3-macos-x86_64-none/lib/python3.13/json/encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Users/apple/.local/share/uv/python/cpython-3.13.3-macos-x86_64-none/lib/python3.13/json/encoder.py", line 261, in iterencode
    return _iterencode(o, 0)
  File "/Users/apple/.local/share/uv/python/cpython-3.13.3-macos-x86_64-none/lib/python3.13/json/encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
                    f'is not JSON serializable')
sqlalchemy.exc.StatementError: (builtins.TypeError) Object of type bytes is not JSON serializable
[SQL: INSERT INTO events (id, app_name, user_id, session_id, invocation_id, author, branch, timestamp, content, actions, long_running_tool_ids_json, grounding_metadata, partial, turn_complete, error_code, error_message, interrupted) VALUES (%(id)s, %(app_name)s, %(user_id)s, %(session_id)s, %(invocation_id)s, %(author)s, %(branch)s, %(timestamp)s, %(content)s::JSONB, %(actions)s, %(long_running_tool_ids_json)s, %(grounding_metadata)s::JSONB, %(partial)s, %(turn_complete)s, %(error_code)s, %(error_message)s, %(interrupted)s)]
[parameters: [{'author': 'Coordinator', 'user_id': 'user', 'app_name': 'bi_agent', 'timestamp': datetime.datetime(2025, 6, 3, 16, 7, 25, 454928), 'long_running_tool ... (1456 characters truncated) ... ', 'turn_complete': None, 'branch': None, 'interrupted': None, 'partial': None, 'grounding_metadata': None, 'error_message': None, 'error_code': None}]]

TTWShell avatar Jun 03 '25 08:06 TTWShell

python --version Python 3.13.3 google-adk==1.1.1

TTWShell avatar Jun 03 '25 08:06 TTWShell

Sorry, I still didn't have a chance to test it in the latest ADK but the similar issue started to happen today even without any code changes to our implementation.

We're using google-adk==0.5.0 and VertexAiSessionService.

Here is the relevant stack trace.

[ERROR] TypeError: Object of type bytes is not JSON serializable
  ...
  File "/app/google/adk/runners.py", line 199, in run_async
    self.session_service.append_event(session=session, event=event)
  File "/app/google/adk/sessions/vertex_ai_session_service.py", line 243, in append_event
    self.api_client.request(
  File "/app/google/genai/_api_client.py", line 765, in request
    response = self._request(http_request, stream=False)
  File "/app/google/genai/_api_client.py", line 665, in _request
    data = json.dumps(http_request.data) if http_request.data else None
  File "/usr/local/lib/python3.11/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/local/lib/python3.11/json/encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/lib/python3.11/json/encoder.py", line 258, in iterencode
    return _iterencode(o, 0)
  File "/usr/local/lib/python3.11/json/encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '

From my observation, event.content.parts[] recently started to contain thought_signature in bytes format and this seemed to cause the above issue related to JSON serialization.

e.g.

{'skip_summarization': None, 'state_delta': {}, 'artifact_delta': {}, 'transfer_agent': None, 'escalate': None, 'requested_auth_configs': {}}, 'content': {'parts': [{'thought': True, 'thought_signature': b'\x01T\xa8\\\xee\x8dQb\...'}

In our case, disabling "thinking" feature as follows solved the issue.

    agent = Agent(
        name="...",
        description="...",
        instruction="...",
        model="gemini-2.5-flash-preview-05-20",
        planner=BuiltInPlanner(
            thinking_config=types.ThinkingConfig(
            include_thoughts=False, thinking_budget=0
        )
    )

Hope this information helps.

okamotoyuki avatar Jun 03 '25 09:06 okamotoyuki

We're having the same issue, it looks like something changed from the Google side, already tried to upgrade to the 1.1.1 but the issue still persists.

Unfortunately we cannot set the thinking_budget to zero because we need thinking to be enabled, so there's no known workaround available.

danilotorrisi avatar Jun 03 '25 10:06 danilotorrisi

Same Issue, Been busting myself since morning.

Apollovishwas avatar Jun 03 '25 10:06 Apollovishwas

Same issue here. Using Gemini 2.5 breaks my code. It works with any other model (Gemini 2.0, or OpenAI, etc).

elmspace avatar Jun 03 '25 16:06 elmspace

Same issue here. Using Gemini 2.5 breaks my code. It works with any other model (Gemini 2.0, or OpenAI, etc).

It's because all of em are thinking model. and It's returning thinking signature bytes

either turn off thinking or use other LLMs.

No idea how long this would take

veevortexiq avatar Jun 03 '25 16:06 veevortexiq

gemini-2.5-flash-preview-04-17 -> Working forcing not to "think" gemini-2.5-flash-preview-05-20 -> Working forcing not to "think"

agent = Agent(
    name=agent_name,
    model=LLM_MODEL,
    description=(
        DESCRIPTION
    ),
    instruction=(
        PROMPT
    ),
    sub_agents=[subagent],
    tools=[tool],
    before_model_callback=build_context,
    planner=BuiltInPlanner(
        thinking_config=types.ThinkingConfig(
            include_thoughts=False, thinking_budget=0
        )
    )
)

hborras avatar Jun 03 '25 18:06 hborras

Hi, thanks for reporting this issue, this should be resolved in the latest 1.2.1 release.

DeanChensj avatar Jun 10 '25 01:06 DeanChensj