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

ValueError: "No function call event found" for function responses in 1.22.1 with SequentialAgent and AgentTool

Open kashirin-dm opened this issue 10 months ago • 9 comments

Describe the bug ValueError: No function call event found for function responses ids occurs in google-adk==1.22.1 when using a SequentialAgent wrapped in an AgentTool. This error signifies a mismatch/missing event in the conversation history, specifically when a sub-agent within the SequentialAgent completes a tool call. Downgrading to google-adk==1.21.0 resolves the issue.

To Reproduce

  1. Define a SequentialAgent that contains LlmAgent sub-agents.
  2. Wrap this SequentialAgent in an AgentTool and provide it to a parent LlmAgent.
  3. Invoke the parent agent such that it delegates to the AgentTool (the SequentialAgent).
  4. Inside the SequentialAgent, one of the sub-agents performs a tool call (e.g., using an MCP tool).
  5. Upon receiving the tool result, the framework fails with:
ValueError: No function call event found for function responses ids: {'adk-xxxx-xxxx-...'}

Stacktrace:

  File ".../google/adk/flows/llm_flows/contents.py", line 442, in _get_contents
    result_events = _rearrange_events_for_latest_function_response(
        filtered_events
    )
  File ".../google/adk/flows/llm_flows/contents.py", line 195, in _rearrange_events_for_latest_function_response
    raise ValueError(
        'No function call event found for function responses ids:'
        f' {function_responses_ids}'
    )
ValueError: No function call event found for function responses ids: {'adk-31549d8b-460a-428c-80ec-edd43bb8c30d'}

Expected behavior The internal InMemorySessionService created by AgentTool should correctly persist and associate function_call events with their subsequent function_response events, allowing the SequentialAgent to continue execution without a ValueError.

Screenshots N/A

Desktop (please complete the following information):

  • OS: macOS (15.2)
  • Python version(python -V): 3.14.0 (also observed on 3.13)
  • ADK version(pip show google-adk): Broken in 1.22.1, works in 1.21.0.

Model Information:

  • Are you using LiteLLM: No
  • Which model is being used: gemini-3-flash-preview (also observed with others)

Additional context The issue seems specific to the nested session logic in AgentTool. AgentTool creates a new InMemorySessionService for each call (agent_tool.py:155). In 1.22.1, it appears that either:

  1. The function_call event is not being correctly appended to the InMemorySession before the _get_contents logic is triggered for the response.
  2. The event filtering logic in contents.py (specifically _rearrange_events_for_latest_function_response) is filtering out the function_call due to branch mismatch or some other criteria introduced/changed in 1.22.1.

kashirin-dm avatar Jan 14 '26 19:01 kashirin-dm

@kashirin-dm Thanks for reporting this issue! Are you using SSE streaming mode or not? If possible, do you mind providing a minimal example code to reproduce this issue?

xuanyang15 avatar Jan 15 '26 18:01 xuanyang15

Hi @xuanyang15,

I have analyzed the root cause and created a minimal reproduction example for this issue.

Root Cause Analysis

The issue is caused by incomplete RunConfig propagation in AgentTool.run_async.

  1. Isolation: AgentTool creates a new Runner and a new InMemorySessionService for the wrapped agent.

  2. Missing Propagation: In AgentTool.run_async, the runner is started without passing the run_config from the parent's InvocationContext.

  3. Mode Mismatch:

    • The parent runner operates in StreamingMode.SSE (default in 1.22.1 for many environments).
    • The inner runner (inside AgentTool) defaults to StreamingMode.NONE.
  4. The Failure Loop:

    • The LLM yields a partial function call (partial=True).
    • The inner BaseLlmFlow processes it immediately (thinking it's in NONE mode).
    • The Runner logic skips appending any event where partial=True to the session history.
    • The tool executes, and a function_response is yielded and appended.
    • On the next turn, _get_contents in contents.py fails to find the matching function_call for that function_response in history, raising the ValueError.
  5. Why it was "working" in 1.21.0:

    • In 1.21.0, StreamingMode.NONE was the effective default, and the PROGRESSIVE_SSE_STREAMING feature was not active.
    • LLMs returned complete, non-partial function calls (partial=False).
    • The Runner correctly appended these complete events to history, even without the propagated RunConfig.
    • In 1.22.1, SSE became the default or more pervasive, causing partial events to be yielded. These partial events are filtered out by the Runner if not in SSE mode, leading to the history gap and ValueError.

Answers to your questions:

  1. Are you using SSE streaming mode? Yes, it is used (enabled by default in 1.22.1), and its mismatch across AgentTool boundaries is exactly what triggers the bug.
  2. Is it specific to MCP tools? No. It happens with any tool when an agent is nested via AgentTool.

Minimal Reproduction Example

Save this as reproduce_bug.py and run it with google-adk==1.22.1:

import asyncio
from typing import AsyncGenerator, List, Optional, Any
from google.adk.agents import Agent, SequentialAgent, LlmAgent, RunConfig, StreamingMode
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.models import BaseLlm, LlmRequest, LlmResponse
from google.adk.tools import AgentTool
from google.genai import types

class MockLLM(BaseLlm):
    model: str
    responses: List[LlmResponse] = []
    current_idx: int = 0

    async def generate_content_async(self, llm_request: LlmRequest, stream: bool = False) -> AsyncGenerator[LlmResponse, None]:
        if self.current_idx < len(self.responses):
            resp = self.responses[self.current_idx]
            self.current_idx += 1
            yield resp
        else:
            yield LlmResponse(content=types.Content(role="model", parts=[types.Part(text="Done")]), partial=False)

async def mock_tool(request: str) -> str:
    return f"Result for {request}"

async def reproduce():
    # 1. Setup nested agent (Sequential + SubAgents)
    sub_agent = Agent(name="SubAgent", model="mock", tools=[mock_tool])
    seq_agent = SequentialAgent(name="SeqAgent", sub_agents=[sub_agent])
    
    # 2. Wrap it in AgentTool
    agent_tool = AgentTool(agent=seq_agent)
    
    # 3. Parent Agent that calls the tool
    parent_llm = MockLLM(model="parent")
    parent_agent = Agent(name="ParentAgent", model="parent", tools=[agent_tool])
    
    # 4. Mock responses to simulate SSE partial function call
    fc = types.FunctionCall(name="SeqAgent", args={"request": "test"}, id="call-1")
    # SubAgent yields a PARTIAL function call (typical for SSE)
    sub_fc = types.FunctionCall(name="mock_tool", args={"request": "inner"}, id="call-inner")
    
    # Parent calls SeqAgent
    parent_llm.responses = [LlmResponse(content=types.Content(role="model", parts=[types.Part(function_call=fc)]), partial=False)]
    
    # SubAgent (inside SeqAgent) yields partial FC
    sub_agent.llm = MockLLM(model="sub")
    sub_agent.llm.responses = [
        LlmResponse(content=types.Content(role="model", parts=[types.Part(function_call=sub_fc)]), partial=True)
    ]

    runner = Runner(agent=parent_agent, session_service=InMemorySessionService(), app_name="BugRepro")
    
    # Run in SSE mode
    config = RunConfig(streaming_mode=StreamingMode.SSE)
    try:
        async for _ in runner.run_async(user_id="u1", session_id="s1", 
                                       new_message=types.Content(role="user", parts=[types.Part(text="start")]),
                                       run_config=config):
            pass
        print("Success (Bug not reproduced)")
    except ValueError as e:
        print(f"Reproduced expected error: {e}")

if __name__ == "__main__":
    asyncio.run(reproduce())

Proposed Fix

In google/adk/tools/agent_tool.py, propagate the run_config to the child runner:

# google/adk/tools/agent_tool.py

    async with Aclosing(
        runner.run_async(
            user_id=session.user_id,
            session_id=session.id,
            new_message=content,
            run_config=tool_context._invocation_context.run_config, # <--- Fix here
        )
    ) as agen:

kashirin-dm avatar Jan 15 '26 20:01 kashirin-dm

@kashirin-dm Thanks for the information! I actually tried with the following agent, which works fine even with streaming mode on (StreamingMode.SSE):

import random

from google.adk.agents import Agent
from google.adk.agents.sequential_agent import SequentialAgent
from google.adk.tools.agent_tool import AgentTool
from google.adk.tools.tool_context import ToolContext


def roll_die(sides: int, tool_context: ToolContext) -> int:
  """Roll a die and return the rolled result.

  Args:
    sides: The integer number of sides the die has.

  Returns:
    An integer of the result of rolling the die.
  """
  result = random.randint(1, sides)
  if not 'rolls' in tool_context.state:
    tool_context.state['rolls'] = []

  tool_context.state['rolls'] = tool_context.state['rolls'] + [result]
  return result


hello_world_agent = Agent(
    model="gemini-3-flash-preview",
    name="hello_world_agent",
    description=(
        "hello world agent that can roll a dice of any number of sides and"
        " check prime numbers."
    ),
    instruction="""
      You roll dice and answer questions about the outcome of the dice rolls.
      Use the roll_die tool to roll a die of 8 sides.
    """,
    tools=[
        roll_die,
    ],
)

# SequentialAgent that runs hello_world_agent
sequential_workflow = SequentialAgent(
    name="sequential_workflow",
    description="A workflow that rolls a dice and checks prime numbers.",
    sub_agents=[hello_world_agent],
)

# Parent agent that uses the SequentialAgent as a tool
root_agent = Agent(
    name="parent_agent",
    model="gemini-3-flash-preview",
    instruction="""You are a helpful assistant. When the user asks you to
    roll a die or check prime numbers, delegate to the
    sequential_workflow tool. Pass the user's request to the tool.""",
    tools=[AgentTool(agent=sequential_workflow)],
)
Image

Could you please have a try?

One thing to call out is that StreamingMode.SSE is not set by default, it is just the Progressive SSE streaming feature is enabled by default when user set RunConfig(streaming_mode=StreamingMode.SSE). If you don't set streaming_mode (i.e. RunConfig()), it will still be StreamingMode.None.

reproduce_bug.py can reproduce the issue because it only emits partial Function calls, no aggregated non-partial function calls. Could you please try calling the real model (instead of mocking it)? Since it will go though google_llm.py, where it utilizes StreamingResponseAggregator to emit both partial and non-partial function calls.

xuanyang15 avatar Jan 15 '26 22:01 xuanyang15

Hi, I believe PROGRESSIVE_SSE_STREAMING is also causing this same "No function call event found" when connecting ADK 1.22.0+ to a CopilotKit frontend. Disabling the feature flag causes behavior to revert to expectations.

KeganHollern avatar Jan 16 '26 15:01 KeganHollern

@KeganHollern Thanks for reporting it! Do you have some example code to reproduce this issue?

With PROGRESSIVE_SSE_STREAMING enabled, ADK will convert LLM streaming chunks into both partial events and aggregated non partial events. For example, if LLM returns:

  • chunk 1: FC1
  • chunk 2: FC 2

ADK will convert them into (done by the StreamingResponseAggregator):

  • event 1: FC1, partial=true
  • event 2: FC2, partial=true
  • event 3: FC1+FC2, partial=False

ADK only stores non partial events into sessions. So, I suspect "No function call event found" is caused by ADK missing the aggregated event (e.g. event 3).

xuanyang15 avatar Jan 16 '26 17:01 xuanyang15

Any updates on this?

gisdakis avatar Jan 21 '26 12:01 gisdakis

I created https://github.com/google/adk-python/commit/d62f9c896c301aba3a781e868735e16f946a8862, but not sure how effective it is since the root cause is still not identified. Do you have some example code (talking to the real model) which can reproduce this issue?

xuanyang15 avatar Jan 22 '26 00:01 xuanyang15

This issue has been automatically marked as stale because it has not had recent activity for 7 days after a maintainer requested clarification. It will be closed if no further activity occurs within 7 days.

adk-bot avatar Jan 29 '26 06:01 adk-bot

This has been automatically closed because it has been marked as stale for over 7 days.

adk-bot avatar Feb 05 '26 06:02 adk-bot