Skip to content

TypeError when using LongRunningFunctionTool: SerializationIterator is not JSON serializable during event DB insert #586

Closed

Description

@JoaoCampista

⚠️ Please make sure you read the contribution guide and file the issues in the right place.
[Contribution guide.](https://google.github.io/adk-docs/contributing-guide/)


Describe the bug

When using a LongRunningFunctionTool with a generator (yielding incremental progress updates), the ADK framework attempts to serialize the generator object itself (SerializationIterator) into the database, causing a TypeError. This leads to a crash when committing the session event to a PostgreSQL database.


To Reproduce

Steps to reproduce the behavior:

  1. Define a generator function wrapped in LongRunningFunctionTool.
  2. Create an agent using LlmAgent.
  3. Serve the agent via FastAPI using get_fast_api_app.
  4. Set SESSION_DB_URL to a PostgreSQL RDS instance.
  5. Send a request that triggers the long-running tool (via /run_sse).
  6. Observe the logs — the generator object fails to serialize and causes a crash.

Expected behavior

Intermediate yields and final return values from the tool should be processed and saved as individual serialized FunctionResponse events. The tool's generator object (SerializationIterator) should not be serialized or stored directly in the database.


Screenshots

N/A — full log provided below.


Desktop (please complete the following information):

  • OS: Windows 11
  • Python version: Python 3.13
  • ADK version: Latest (as of May 2025)
  • DB: PostgreSQL RDS

Code (minimal reproducible example)

agent.py

from google.adk.agents import LlmAgent
from google.adk.tools.long_running_tool import LongRunningFunctionTool 
import time

def long_task(*args, **kwargs):
    yield {"status": "pending", "message": "Starting task..."}
    time.sleep(2)
    yield {"status": "pending", "progress": 50}
    time.sleep(4)
    return {"status": "completed", "result": "Final outcome"}

root_agent = LlmAgent(
    model="gemini-2.0-flash",
    name="ProposalsAgent",
    description="A nice assistante that call the long_task tool",
    tools=[LongRunningFunctionTool(long_task)],
)

main.py

from fastapi import FastAPI
from google.adk.cli.fast_api import get_fast_api_app
from dotenv import load_dotenv
import os

load_dotenv()

AGENT_DIR = os.getenv("AGENT_DIR")
SESSION_DB_URL = os.getenv("SESSION_DB_URL")

app: FastAPI = get_fast_api_app(
    agent_dir=AGENT_DIR,
    session_db_url=SESSION_DB_URL,
    allow_origins=["*"],
    web=True
)

Full Log Output

INFO:     127.0.0.1:56658 - "POST /run_sse HTTP/1.1" 200 OK
INFO:C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\google\adk\cli\utils\envs.py:Loaded .env file for teste at C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.env
INFO:google.adk.sessions.database_session_service:Append event: content=Content(parts=[Part(video_metadata=None, thought=None, code_execution_result=None, executable_code=None, file_data=None, function_call=None, function_response=None, inline_data=None, text='chame a tool')], role='user') grounding_metadata=None partial=None turn_complete=None error_code=None error_message=None interrupted=None custom_metadata=None invocation_id='e-a5d0b5db-a4b2-490d-8d56-5a47112649c6' author='user' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}) long_running_tool_ids=None branch=None id='CVFoDJX1' timestamp=1746545843.645539 to session f61e7626-fa90-4969-96da-d0f621c055bc
INFO:google.adk.models.google_llm:Sending out request, model: gemini-2.0-flash, backend: ml_dev, stream: False
INFO:google.adk.models.google_llm:
LLM Request:
-----------------------------------------------------------
System Instruction:
You are an agent. Your internal name is "ProposalsAgent".

 The description about you is "A nice assistante that call the long_task tool"
-----------------------------------------------------------
Contents:
{"parts":[{"text":"chame a tool"}],"role":"user"}
-----------------------------------------------------------
Functions:
long_task: {} -> None
-----------------------------------------------------------

INFO:google_genai.models:AFC is enabled with max remote calls: 10.
INFO:httpx:HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent "HTTP/1.1 200 OK"
WARNING:google_genai.types:Warning: there are non-text parts in the response: ['function_call'],returning concatenated text result from text parts,check out the non text parts for full response from model.
INFO:google.adk.models.google_llm:
LLM Response:
-----------------------------------------------------------
Text:
None
-----------------------------------------------------------
Function calls:
name: long_task, args: {}
-----------------------------------------------------------
Raw response:
{"candidates":[{"content":{"parts":[{"function_call":{"args":{},"name":"long_task"}}],"role":"model"},"finish_reason":"STOP","avg_logprobs":-0.000011800671927630901}],"model_version":"gemini-2.0-flash","usage_metadata":{"candidates_token_count":3,"candidates_tokens_details":[{"modality":"TEXT","token_count":3}],"prompt_token_count":39,"prompt_tokens_details":[{"modality":"TEXT","token_count":39}],"total_token_count":42},"automatic_function_calling_history":[]}
-----------------------------------------------------------

INFO:google.adk.sessions.database_session_service:Append event: content=Content(parts=[Part(video_metadata=None, thought=None, code_execution_result=None, executable_code=None, file_data=None, function_call=FunctionCall(id='adk-95a62e89-3367-4eef-a308-ee64c156e256', args={}, name='long_task'), function_response=None, inline_data=None, text=None)], role='model') grounding_metadata=None partial=None turn_complete=None error_code=None error_message=None interrupted=None custom_metadata=None invocation_id='e-a5d0b5db-a4b2-490d-8d56-5a47112649c6' author='ProposalsAgent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}) long_running_tool_ids={'adk-95a62e89-3367-4eef-a308-ee64c156e256'} branch=None id='jhonJAcn' timestamp=1746545845.252927 to session f61e7626-fa90-4969-96da-d0f621c055bc
INFO:google.adk.cli.fast_api:Generated event in agent run streaming: {"content":{"parts":[{"functionCall":{"id":"adk-95a62e89-3367-4eef-a308-ee64c156e256","args":{},"name":"long_task"}}],"role":"model"},"invocation_id":"e-a5d0b5db-a4b2-490d-8d56-5a47112649c6","author":"ProposalsAgent","actions":{"state_delta":{},"artifact_delta":{},"requested_auth_configs":{}},"long_running_tool_ids":["adk-95a62e89-3367-4eef-a308-ee64c156e256"],"id":"jhonJAcn","timestamp":1746545845.252927}
INFO:google.adk.sessions.database_session_service:Append event: content=Content(parts=[Part(video_metadata=None, thought=None, code_execution_result=None, executable_code=None, file_data=None, function_call=None, function_response=FunctionResponse(id='adk-95a62e89-3367-4eef-a308-ee64c156e256', name='long_task', response={'result': <generator object long_task at 0x000001E3D1246670>}), inline_data=None, text=None)], role='user') grounding_metadata=None partial=None turn_complete=None error_code=None error_message=None interrupted=None custom_metadata=None invocation_id='e-a5d0b5db-a4b2-490d-8d56-5a47112649c6' author='ProposalsAgent' actions=EventActions(skip_summarization=None, state_delta={}, artifact_delta={}, transfer_to_agent=None, escalate=None, requested_auth_configs={}) long_running_tool_ids=None branch=None id='9p63RdCQ' timestamp=1746545848.549715 to session f61e7626-fa90-4969-96da-d0f621c055bc
ERROR:google.adk.cli.fast_api:Error in event_generator: (builtins.TypeError) Object of type SerializationIterator 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: [{'content': {'parts': [{'function_response': {'id': 'adk-95a62e89-3367-4eef-a308-ee64c156e256', 'name': 'long_task', 'response': {'result': Serializat ... (551 characters truncated) ... ing_tool_ids_json': None, 'interrupted': None, 'partial': None, 'turn_complete': None, 'grounding_metadata': None, 'error_code': None, 'branch': None}]]
Traceback (most recent call last):
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1812, in _execute_context
    context = constructor(
        dialect, self, conn, execution_options, *args, **kw
    )
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\engine\default.py", line 1521, in _init_compiled
    flattened_processors[key](compiled_params[key])
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\sql\type_api.py", line 2096, in process
    return fixed_impl_processor(
        fixed_process_param(value, dialect)
    )
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\sql\sqltypes.py", line 2779, in process
    return json_serializer(value)
  File "C:\Python313\Lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^^^
  File "C:\Python313\Lib\json\encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python313\Lib\json\encoder.py", line 261, in iterencode
    return _iterencode(o, 0)
  File "C:\Python313\Lib\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 SerializationIterator is not JSON serializable

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

Traceback (most recent call last):
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\google\adk\cli\fast_api.py", line 626, in event_generator
    async for event in runner.run_async(
    ...<8 lines>...
      yield f"data: {sse_event}\n\n"
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\google\adk\runners.py", line 199, in run_async
    self.session_service.append_event(session=session, event=event)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\google\adk\sessions\database_session_service.py", line 548, in append_event 
    sessionFactory.commit()
    ~~~~~~~~~~~~~~~~~~~~~^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\session.py", line 2032, in commit
    trans.commit(_to_root=True)
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^
  File "<string>", line 2, in commit
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\state_changes.py", line 139, in _go
    ret_value = fn(self, *arg, **kw)
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\session.py", line 1313, in commit
    self._prepare_impl()
    ~~~~~~~~~~~~~~~~~~^^
  File "<string>", line 2, in _prepare_impl
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\state_changes.py", line 139, in _go
    ret_value = fn(self, *arg, **kw)
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\session.py", line 1288, in _prepare_impl
    self.session.flush()
    ~~~~~~~~~~~~~~~~~~^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\session.py", line 4353, in flush
    self._flush(objects)
    ~~~~~~~~~~~^^^^^^^^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\session.py", line 4488, in _flush
    with util.safe_reraise():
         ~~~~~~~~~~~~~~~~~^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\util\langhelpers.py", line 146, in __exit__
    raise exc_value.with_traceback(exc_tb)
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\session.py", line 4449, in _flush
    flush_context.execute()
    ~~~~~~~~~~~~~~~~~~~~~^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\unitofwork.py", line 466, in execute
    rec.execute(self)
    ~~~~~~~~~~~^^^^^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\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 "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\persistence.py", line 93, in save_obj
    _emit_insert_statements(
    ~~~~~~~~~~~~~~~~~~~~~~~^
        base_mapper,
        ^^^^^^^^^^^^
    ...<3 lines>...
        insert,
        ^^^^^^^
    )
    ^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\orm\persistence.py", line 1048, in _emit_insert_statements       
    result = connection.execute(
        statement, multiparams, execution_options=execution_options
    )
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1416, in execute
    return meth(
        self,
        distilled_parameters,
        execution_options or NO_OPTIONS,
    )
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\sql\elements.py", line 523, in _execute_on_connection
    return connection._execute_clauseelement(
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        self, distilled_params, execution_options
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1638, in _execute_clauseelement
    ret = self._execute_context(
        dialect,
    ...<8 lines>...
        cache_hit=cache_hit,
    )
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1818, in _execute_context
    self._handle_dbapi_exception(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        e, str(statement), parameters, None, None
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\engine\base.py", line 2352, in _handle_dbapi_exception
    raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1812, in _execute_context
    context = constructor(
        dialect, self, conn, execution_options, *args, **kw
    )
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\engine\default.py", line 1521, in _init_compiled
    flattened_processors[key](compiled_params[key])
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\sql\type_api.py", line 2096, in process
    return fixed_impl_processor(
        fixed_process_param(value, dialect)
    )
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\sqlalchemy\sql\sqltypes.py", line 2779, in process
    return json_serializer(value)
  File "C:\Python313\Lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^^^
  File "C:\Python313\Lib\json\encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python313\Lib\json\encoder.py", line 261, in iterencode
    return _iterencode(o, 0)
  File "C:\Python313\Lib\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 SerializationIterator 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: [{'content': {'parts': [{'function_response': {'id': 'adk-95a62e89-3367-4eef-a308-ee64c156e256', 'name': 'long_task', 'response': {'result': Serializat ... (551 characters truncated) ... ing_tool_ids_json': None, 'interrupted': None, 'partial': None, 'turn_complete': None, 'grounding_metadata': None, 'error_code': None, 'branch': None}]]
ERROR:opentelemetry.context:Failed to detach context
Traceback (most recent call last):
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\trace\__init__.py", line 587, in use_span
    yield span
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\sdk\trace\__init__.py", line 1105, in start_as_current_span   
    yield span
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\trace\__init__.py", line 452, in start_as_current_span        
    yield span
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\google\adk\agents\base_agent.py", line 128, in run_async
    yield event
GeneratorExit

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\context\__init__.py", line 155, in detach
    _RUNTIME_CONTEXT.detach(token)
    ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\context\contextvars_context.py", line 53, in detach
    self._current_context.reset(token)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^
    _RUNTIME_CONTEXT.detach(token)
    ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\context\contextvars_context.py", line 53, in detach
    self._current_context.reset(token)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^
    ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\context\contextvars_context.py", line 53, in detach
    self._current_context.reset(token)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^
    self._current_context.reset(token)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^
ValueError: <Token var=<ContextVar name='current_context' default={} at 0x000001E3C38CA610> at 0x000001E3D0238080> was created in a different Context
ERROR:opentelemetry.context:Failed to detach context
ValueError: <Token var=<ContextVar name='current_context' default={} at 0x000001E3C38CA610> at 0x000001E3D0238080> was created in a different Context
ERROR:opentelemetry.context:Failed to detach context
Traceback (most recent call last):
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\trace\__init__.py", line 587, in use_span
Traceback (most recent call last):
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\trace\__init__.py", line 587, in use_span
    yield span
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\sdk\trace\__init__.py", line 1105, in start_as_current_span   
    yield span
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\sdk\trace\__init__.py", line 1105, in start_as_current_span   
    yield span
    yield span
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\trace\__init__.py", line 452, in start_as_current_span        
    yield span
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\trace\__init__.py", line 452, in start_as_current_span        
    yield span
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\google\adk\flows\llm_flows\base_llm_flow.py", line 487, in _call_llm_async  
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\google\adk\flows\llm_flows\base_llm_flow.py", line 487, in _call_llm_async  
    yield llm_response
    yield llm_response
GeneratorExit
GeneratorExit

During handling of the above exception, another exception occurred:

  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\context\__init__.py", line 155, in detach
    _RUNTIME_CONTEXT.detach(token)
    ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^
  File "C:\Users\JoaoC\Nextcloud\Projetos\Lugui\Agents\ai-ecs-agents\.venv\Lib\site-packages\opentelemetry\context\contextvars_context.py", line 53, in detach
    self._current_context.reset(token)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^
ValueError: <Token var=<ContextVar name='current_context' default={} at 0x000001E3C38CA610> at 0x000001E3D023A600> was created in a different Context

Additional context

The error seems to occur specifically when the framework attempts to insert the function response (which contains a generator) into the events table of the session database. The ADK is passing a SerializationIterator (a generator object) directly inside the response.result field of a FunctionResponse, which is not JSON serializable.

This suggests that instead of serializing and storing each yielded result from the tool incrementally, the full generator is being included in the database payload. This causes a TypeError during the SQLAlchemy .commit() operation:

TypeError: Object of type SerializationIterator is not JSON serializable

The stack trace points to this during an INSERT INTO events (...) VALUES (...) SQL command.

This likely needs to be handled either by:

  • Consuming and serializing the generator before persisting the event; or
  • Updating the ADK's internal serialization logic to properly handle streamed results from LongRunningFunctionTool.

Activity

  1. added
    services
    on May 6, 2025
  2. added theissue type on May 6, 2025
  3. added
    tools
    and removed
    services
    on May 6, 2025
  4. changed the issue type fromtoon May 28, 2025
  5. seanzhou1023 commented on May 28, 2025

    @seanzhou1023
    Collaborator

    we don't support return generator in the tool so far

  6. added this to the Feature Roadmap milestone on Jun 2, 2025
  7. amaykumar commented on Jun 2, 2025

    @amaykumar

    +1 for this feature!

    We have a streaming tool which generates responses as it receives batched data from the backend API. It throws following error while testing with adk web:

    ERROR - fast_api.py:708 - Error in event_generator: Unable to serialize unknown type: <class 'async_generator'>

  8. nileshtrivedi commented on Jun 10, 2025

    @nileshtrivedi

    I get a different error: {"error": "cannot pickle 'generator' object"} when I try to run a minimal agent via adk web. Here is my full code for agent.py:

    import datetime
    import time
    from zoneinfo import ZoneInfo
    from google.adk.agents import Agent
    from google.adk.tools import LongRunningFunctionTool
    
    def perform_research(*args, **kwargs):
        yield {"status": "pending", "message": "Starting task..."}
        time.sleep(2)
        yield {"status": "pending", "progress": 20}
        time.sleep(3)
        yield {"status": "pending", "progress": 50}
        time.sleep(4)
        return {"status": "completed", "result": "Final outcome"}
    
    root_agent = Agent(
        name="weather_time_agent",
        model="gemini-2.0-flash",
        description=(
            "Agent to answer questions about the time and weather in a city."
        ),
        instruction=(
            "You are a helpful agent who can answer user questions by calling tools."
        ),
        tools=[LongRunningFunctionTool(func=perform_research)],
    )
    

    Full error logs:

    2025-06-10 16:17:35,355 - INFO - google_llm.py:148 -
    LLM Response:
    -----------------------------------------------------------
    Text:
    None
    -----------------------------------------------------------
    Function calls:
    name: perform_research, args: {}
    -----------------------------------------------------------
    Raw response:
    {"candidates":[{"content":{"parts":[{"function_call":{"args":{},"name":"perform_research"}}],"role":"model"},"finish_reason":"STOP","avg_logprobs":-0.05302940309047699}],"model_version":"gemini-2.0-flash","usage_metadata":{"candidates_token_count":3,"candidates_tokens_details":[{"modality":"TEXT","token_count":3}],"prompt_token_count":59,"prompt_tokens_details":[{"modality":"TEXT","token_count":59}],"total_token_count":62},"automatic_function_calling_history":[]}
    -----------------------------------------------------------
    
    2025-06-10 16:17:35,358 - INFO - fast_api.py:814 - Generated event in agent run streaming: {"content":{"parts":[{"functionCall":{"id":"adk-33347256-5e1d-4880-9030-c1e089aee6fc","args":{},"name":"perform_research"}}],"role":"model"},"usageMetadata":{"candidatesTokenCount":3,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":3}],"promptTokenCount":59,"promptTokensDetails":[{"modality":"TEXT","tokenCount":59}],"totalTokenCount":62},"invocationId":"e-ffdf20e3-fee6-47cc-959c-189e39b3c14f","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"longRunningToolIds":["adk-33347256-5e1d-4880-9030-c1e089aee6fc"],"id":"3wpPcQUT","timestamp":1749552454.522432}
    2025-06-10 16:17:35,358 - INFO - fast_api.py:814 - Generated event in agent run streaming: {"content":{"parts":[{"functionCall":{"id":"adk-33347256-5e1d-4880-9030-c1e089aee6fc","args":{},"name":"perform_research"}}],"role":"model"},"usageMetadata":{"candidatesTokenCount":3,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":3}],"promptTokenCount":59,"promptTokensDetails":[{"modality":"TEXT","tokenCount":59}],"totalTokenCount":62},"invocationId":"e-ffdf20e3-fee6-47cc-959c-189e39b3c14f","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"longRunningToolIds":["adk-33347256-5e1d-4880-9030-c1e089aee6fc"],"id":"3wpPcQUT","timestamp":1749552454.522432}
    
    2025-06-10 16:17:44,373 - INFO - fast_api.py:814 - Generated event in agent run streaming: {"content":{"parts":[{"functionResponse":{"id":"adk-33347256-5e1d-4880-9030-c1e089aee6fc","name":"perform_research","response":{"result":[]}}}],"role":"user"},"invocationId":"e-ffdf20e3-fee6-47cc-959c-189e39b3c14f","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"RFFhS7Ze","timestamp":1749552455.361757}
    2025-06-10 16:17:44,373 - INFO - fast_api.py:814 - Generated event in agent run streaming: {"content":{"parts":[{"functionResponse":{"id":"adk-33347256-5e1d-4880-9030-c1e089aee6fc","name":"perform_research","response":{"result":[]}}}],"role":"user"},"invocationId":"e-ffdf20e3-fee6-47cc-959c-189e39b3c14f","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"RFFhS7Ze","timestamp":1749552455.361757}
    2025-06-10 16:17:44,383 - ERROR - fast_api.py:817 - Error in event_generator: cannot pickle 'generator' object
    
    ...
    INFO:     127.0.0.1:56125 - "GET /apps/longrunning/users/user/sessions/094cbefa-6a32-4b6c-9d76-01f711dae709 HTTP/1.1" 500 Internal Server Error
    ERROR:    Exception in ASGI application
    Traceback (most recent call last):
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/uvicorn/protocols/http/httptools_impl.py", line 409, in run_asgi
        result = await app(  # type: ignore[func-returns-value]
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
        return await self.app(scope, receive, send)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/fastapi/applications.py", line 1054, in __call__
        await super().__call__(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/applications.py", line 113, in __call__
        await self.middleware_stack(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/middleware/errors.py", line 187, in __call__
        raise exc
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/middleware/errors.py", line 165, in __call__
        await self.app(scope, receive, _send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 62, in __call__
        await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
        raise exc
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
        await app(scope, receive, sender)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 715, in __call__
        await self.middleware_stack(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 735, in app
        await route.handle(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 288, in handle
        await self.app(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 76, in app
        await wrap_app_handling_exceptions(app, request)(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
        raise exc
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
        await app(scope, receive, sender)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 73, in app
        response = await f(request)
                   ^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/fastapi/routing.py", line 301, in app
        raw_response = await run_endpoint_function(
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/fastapi/routing.py", line 212, in run_endpoint_function
        return await dependant.call(**values)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/google/adk/cli/fast_api.py", line 395, in get_session
        session = await session_service.get_session(
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/google/adk/sessions/in_memory_session_service.py", line 117, in get_session
        return self._get_session_impl(
               ^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/google/adk/sessions/in_memory_session_service.py", line 156, in _get_session_impl
        copied_session = copy.deepcopy(session)
                         ^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 196, in _deepcopy_list
        append(deepcopy(a, memo))
               ^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 196, in _deepcopy_list
        append(deepcopy(a, memo))
               ^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 151, in deepcopy
        rv = reductor(4)
             ^^^^^^^^^^^
    TypeError: cannot pickle 'generator' object
    
  9. Tyrooon commented on Jun 19, 2025

    @Tyrooon

    I get a different error: {"error": "cannot pickle 'generator' object"} when I try to run a minimal agent via adk web. Here is my full code for agent.py:

    import datetime
    import time
    from zoneinfo import ZoneInfo
    from google.adk.agents import Agent
    from google.adk.tools import LongRunningFunctionTool
    
    def perform_research(*args, **kwargs):
        yield {"status": "pending", "message": "Starting task..."}
        time.sleep(2)
        yield {"status": "pending", "progress": 20}
        time.sleep(3)
        yield {"status": "pending", "progress": 50}
        time.sleep(4)
        return {"status": "completed", "result": "Final outcome"}
    
    root_agent = Agent(
        name="weather_time_agent",
        model="gemini-2.0-flash",
        description=(
            "Agent to answer questions about the time and weather in a city."
        ),
        instruction=(
            "You are a helpful agent who can answer user questions by calling tools."
        ),
        tools=[LongRunningFunctionTool(func=perform_research)],
    )
    

    Full error logs:

    2025-06-10 16:17:35,355 - INFO - google_llm.py:148 -
    LLM Response:
    -----------------------------------------------------------
    Text:
    None
    -----------------------------------------------------------
    Function calls:
    name: perform_research, args: {}
    -----------------------------------------------------------
    Raw response:
    {"candidates":[{"content":{"parts":[{"function_call":{"args":{},"name":"perform_research"}}],"role":"model"},"finish_reason":"STOP","avg_logprobs":-0.05302940309047699}],"model_version":"gemini-2.0-flash","usage_metadata":{"candidates_token_count":3,"candidates_tokens_details":[{"modality":"TEXT","token_count":3}],"prompt_token_count":59,"prompt_tokens_details":[{"modality":"TEXT","token_count":59}],"total_token_count":62},"automatic_function_calling_history":[]}
    -----------------------------------------------------------
    
    2025-06-10 16:17:35,358 - INFO - fast_api.py:814 - Generated event in agent run streaming: {"content":{"parts":[{"functionCall":{"id":"adk-33347256-5e1d-4880-9030-c1e089aee6fc","args":{},"name":"perform_research"}}],"role":"model"},"usageMetadata":{"candidatesTokenCount":3,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":3}],"promptTokenCount":59,"promptTokensDetails":[{"modality":"TEXT","tokenCount":59}],"totalTokenCount":62},"invocationId":"e-ffdf20e3-fee6-47cc-959c-189e39b3c14f","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"longRunningToolIds":["adk-33347256-5e1d-4880-9030-c1e089aee6fc"],"id":"3wpPcQUT","timestamp":1749552454.522432}
    2025-06-10 16:17:35,358 - INFO - fast_api.py:814 - Generated event in agent run streaming: {"content":{"parts":[{"functionCall":{"id":"adk-33347256-5e1d-4880-9030-c1e089aee6fc","args":{},"name":"perform_research"}}],"role":"model"},"usageMetadata":{"candidatesTokenCount":3,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":3}],"promptTokenCount":59,"promptTokensDetails":[{"modality":"TEXT","tokenCount":59}],"totalTokenCount":62},"invocationId":"e-ffdf20e3-fee6-47cc-959c-189e39b3c14f","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"longRunningToolIds":["adk-33347256-5e1d-4880-9030-c1e089aee6fc"],"id":"3wpPcQUT","timestamp":1749552454.522432}
    
    2025-06-10 16:17:44,373 - INFO - fast_api.py:814 - Generated event in agent run streaming: {"content":{"parts":[{"functionResponse":{"id":"adk-33347256-5e1d-4880-9030-c1e089aee6fc","name":"perform_research","response":{"result":[]}}}],"role":"user"},"invocationId":"e-ffdf20e3-fee6-47cc-959c-189e39b3c14f","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"RFFhS7Ze","timestamp":1749552455.361757}
    2025-06-10 16:17:44,373 - INFO - fast_api.py:814 - Generated event in agent run streaming: {"content":{"parts":[{"functionResponse":{"id":"adk-33347256-5e1d-4880-9030-c1e089aee6fc","name":"perform_research","response":{"result":[]}}}],"role":"user"},"invocationId":"e-ffdf20e3-fee6-47cc-959c-189e39b3c14f","author":"weather_time_agent","actions":{"stateDelta":{},"artifactDelta":{},"requestedAuthConfigs":{}},"id":"RFFhS7Ze","timestamp":1749552455.361757}
    2025-06-10 16:17:44,383 - ERROR - fast_api.py:817 - Error in event_generator: cannot pickle 'generator' object
    
    ...
    INFO:     127.0.0.1:56125 - "GET /apps/longrunning/users/user/sessions/094cbefa-6a32-4b6c-9d76-01f711dae709 HTTP/1.1" 500 Internal Server Error
    ERROR:    Exception in ASGI application
    Traceback (most recent call last):
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/uvicorn/protocols/http/httptools_impl.py", line 409, in run_asgi
        result = await app(  # type: ignore[func-returns-value]
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
        return await self.app(scope, receive, send)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/fastapi/applications.py", line 1054, in __call__
        await super().__call__(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/applications.py", line 113, in __call__
        await self.middleware_stack(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/middleware/errors.py", line 187, in __call__
        raise exc
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/middleware/errors.py", line 165, in __call__
        await self.app(scope, receive, _send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 62, in __call__
        await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
        raise exc
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
        await app(scope, receive, sender)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 715, in __call__
        await self.middleware_stack(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 735, in app
        await route.handle(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 288, in handle
        await self.app(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 76, in app
        await wrap_app_handling_exceptions(app, request)(scope, receive, send)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
        raise exc
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
        await app(scope, receive, sender)
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/starlette/routing.py", line 73, in app
        response = await f(request)
                   ^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/fastapi/routing.py", line 301, in app
        raw_response = await run_endpoint_function(
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/fastapi/routing.py", line 212, in run_endpoint_function
        return await dependant.call(**values)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/google/adk/cli/fast_api.py", line 395, in get_session
        session = await session_service.get_session(
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/google/adk/sessions/in_memory_session_service.py", line 117, in get_session
        return self._get_session_impl(
               ^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/google/adk/sessions/in_memory_session_service.py", line 156, in _get_session_impl
        copied_session = copy.deepcopy(session)
                         ^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 196, in _deepcopy_list
        append(deepcopy(a, memo))
               ^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 196, in _deepcopy_list
        append(deepcopy(a, memo))
               ^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 143, in deepcopy
        y = copier(memo)
            ^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/site-packages/pydantic/main.py", line 840, in __deepcopy__
        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 136, in deepcopy
        y = copier(x, memo)
            ^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 221, in _deepcopy_dict
        y[deepcopy(key, memo)] = deepcopy(value, memo)
                                 ^^^^^^^^^^^^^^^^^^^^^
      File "/Users/nt/.asdf/installs/python/3.12.8/lib/python3.12/copy.py", line 151, in deepcopy
        rv = reductor(4)
             ^^^^^^^^^^^
    TypeError: cannot pickle 'generator' object
    

    I got exactly the same problems! I want to use LongRunningFunctionCall to load big file while I don't need to wait for the long loading progress. How can I solve it?

  10. MicoRobot commented on Jun 26, 2025

    @MicoRobot

    @Tyrooon @hangfei Are there any solutions to the same problem?

  11. self-assigned this
    on Oct 7, 2025
  12. klateefa commented on Oct 7, 2025

    @klateefa

    Hi @JoaoCampista and thanks to everyone who participated in this thread.

    We're currently doing some housekeeping on our issue tracker. Given the rapid pace of development and the number of updates since this was last active, there's a good chance this issue has been resolved in a newer version. To help us keep our backlog focused on current issues, we are closing this as stale.

    If you're still facing this problem, could you please update to the very latest version of the library and confirm the issue still exists? If it does, please comment here, and we will be happy to reopen this issue and investigate further.

    Thanks for your contribution and understanding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

tools

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions