Repository navigation
Closed
Labels
core[Component] This issue is related to the core interface and implementation[Component] This issue is related to the core interface and implementation
Description
** Please make sure you read the contribution guide and file the issues in the right place. **
Contribution guide.
Describe the bug
When an Agent is configured with both output_schema and tools in v1.18.0, the agent repeatedly calls the tool indefinitely instead of using the tool's response to generate the final structured output.
To Reproduce
AI generated code demonstrating the issue
dependencies installed:
requires-python = ">=3.12"
dependencies = [
"backoff>=2.2.1",
"cloudpickle>=3.1.1",
"google-adk[eval]>=1.18.0",
"google-cloud-aiplatform[adk,agent-engines]>=1.120.0",
"google-cloud-secret-manager>=2.16.0",
"google-cloud-bigquery>=3.25.0",
"google-cloud-run>=0.11.0",
"google-cloud-logging>=3.11.0",
]
"""
Minimal reproduction case for ADK infinite loop issue.
This test demonstrates the problem where an agent with both output_schema and tools
may infinite loop when the tool is called repeatedly instead of producing final output.
Issue: When an agent has both output_schema and tools configured, it may repeatedly
call the tool instead of using the tool's response to generate the final output.
"""
import asyncio
import logging
import os
from typing import Any
import vertexai
from google.adk.agents import Agent
from google.adk.tools import FunctionTool, ToolContext
from pydantic import BaseModel, Field
from vertexai.preview import reasoning_engines
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s [%(name)s:%(lineno)d] - %(message)s",
)
logger = logging.getLogger(__name__)
class SimpleResult(BaseModel):
"""Simple output schema with just two fields."""
status: bool = Field(description="Whether the validation was successful")
message: str = Field(description="A message explaining the result")
def simple_validate(tool_context: ToolContext) -> dict[str, Any]:
"""
A simple validation tool that returns data matching SimpleResult schema.
Returns:
Dict with 'status' (bool) and 'message' (str) fields
"""
[logger.info](http://logger.info/)("🔧 simple_validate tool called")
result = {"status": True, "message": "Validation successful"}
[logger.info](http://logger.info/)(f"🔧 simple_validate returning: {result}")
return result
test_agent = Agent(
name="SimpleTestAgent",
model="gemini-2.5-flash",
description="A minimal test agent with output_schema and a tool.",
instruction="""You are a simple validation agent.
**Your task:**
1. Call the simple_validate tool ONCE
2. Use the tool's response to create your final output
3. DO NOT call the tool more than once
**Critical:**
- After receiving the tool response, produce your final SimpleResult output
- The tool returns a dict with 'status' and 'message' fields
- Use these values directly in your output
""",
output_schema=SimpleResult,
output_key="validation_result",
tools=[FunctionTool(func=simple_validate)],
disallow_transfer_to_parent=True,
disallow_transfer_to_peers=True,
)
async def run_minimal_test():
"""Run a minimal test to reproduce the infinite loop issue."""
project_id = os.getenv("GOOGLE_CLOUD_PROJECT", "prodject_id")
location = os.getenv("GOOGLE_CLOUD_LOCATION", "europe-west1")
[logger.info](http://logger.info/)(
f"Initialising Vertex AI with project={project_id}, location={location}"
)
vertexai.init(project=project_id, location=location)
[logger.info](http://logger.info/)("Creating AdkApp with minimal test agent")
app = reasoning_engines.AdkApp(agent=test_agent)
test_message = "Please validate this request"
[logger.info](http://logger.info/)(f"Running test with message: '{test_message}'")
[logger.info](http://logger.info/)("=" * 80)
try:
session = app.create_session(user_id="test-user-minimal")
[logger.info](http://logger.info/)(f"Created session: {[session.id](http://session.id/)}")
event_count = 0
tool_call_count = 0
max_events = 50
[logger.info](http://logger.info/)(f"Starting event stream (max {max_events} events)...")
[logger.info](http://logger.info/)("=" * 80)
async for event in app.async_stream_query(
user_id="test-user-minimal",
session_id=[session.id](http://session.id/),
message=test_message,
):
event_count += 1
event_str = str(event)
if "simple_validate" in event_str:
tool_call_count += 1
logger.warning(
f"⚠️ Event {event_count}: TOOL CALL #{tool_call_count} - simple_validate"
)
else:
[logger.info](http://logger.info/)(f"📝 Event {event_count}: {event}")
if event_count >= max_events:
logger.error(f"🛑 STOPPING: Reached maximum event count ({max_events})")
logger.error(
f"🛑 Tool was called {tool_call_count} times - INFINITE LOOP DETECTED"
)
break
[logger.info](http://logger.info/)("=" * 80)
if tool_call_count > 1:
logger.error(
f"❌ TEST FAILED: Tool was called {tool_call_count} times (expected: 1)"
)
logger.error(
"❌ This confirms the infinite loop issue with output_schema + tools"
)
else:
[logger.info](http://logger.info/)(
f"✓ TEST PASSED: Tool was called {tool_call_count} time(s) as expected"
)
[logger.info](http://logger.info/)(f"✓ Total events: {event_count}")
except Exception as e:
logger.error(f"✗ Test FAILED with error: {type(e).__name__}: {e}")
logger.exception("Full traceback:")
def main():
"""Entry point for the minimal reproduction test."""
[logger.info](http://logger.info/)("=" * 80)
[logger.info](http://logger.info/)("MINIMAL REPRODUCTION CASE: ADK output_schema + tools infinite loop")
[logger.info](http://logger.info/)("=" * 80)
[logger.info](http://logger.info/)("")
[logger.info](http://logger.info/)("Configuration:")
[logger.info](http://logger.info/)(" - Agent: SimpleTestAgent")
[logger.info](http://logger.info/)(" - Output Schema: SimpleResult (status: bool, message: str)")
[logger.info](http://logger.info/)(" - Tool: simple_validate (returns matching schema)")
[logger.info](http://logger.info/)(" - Expected: Tool called ONCE, then agent produces final output")
[logger.info](http://logger.info/)(" - Actual: Will observe if tool is called repeatedly (infinite loop)")
[logger.info](http://logger.info/)("")
[logger.info](http://logger.info/)("=" * 80)
asyncio.run(run_minimal_test())
[logger.info](http://logger.info/)("")
[logger.info](http://logger.info/)("=" * 80)
[logger.info](http://logger.info/)("TEST COMPLETED")
[logger.info](http://logger.info/)("=" * 80)
if __name__ == "__main__":
main()- Provide error or stacktrace
Expected behavior
This example should calls the simple_validate tool just the once but instead it runs infinitly or in this example until the max_events is readed 50 tool calls.
Metadata
Metadata
Assignees
Labels
core[Component] This issue is related to the core interface and implementation[Component] This issue is related to the core interface and implementation
Activity
xuanyang15 commentedon Nov 6, 2025
I can reproduce this issue with the following simplified agent:
I looked in the log, with the follow request to the model:
The model returns function again:
It seems that the model doesn't handle function calls correctly.
xuanyang15 commentedon Nov 6, 2025
@tommyhutcheson Thanks for reporting this issue! While we are debugging this issue, you can use Gemini API (use
GOOGLE_API_KEY=), instead of Vertex API (GOOGLE_GENAI_USE_VERTEXAI=1) to bypass this problem.pedrodotavila commentedon Nov 6, 2025
Hi, I'm having same issue Is there an ETA for this bug?
xuanyang15 commentedon Nov 6, 2025
@pedrodotavila Could you please share your code?
I actually tried with a different agent:
It works fine:
pedrodotavila commentedon Nov 6, 2025
I tried to move all my code to this snippet, so maybe some imports aren't working, i cant share the prompts, sorry.
@xuanyang15
xuanyang15 commentedon Nov 6, 2025
Thank you @pedrodotavila! I'm suspecting it is a model quality issue, will check with the model team. In the meantime, do you mind trying the weather agent in #3413 (comment)? see if it works for you.
pedrodotavila commentedon Nov 6, 2025
@xuanyang15 I wanted to do use google search tool, and as you may know I cant use it as a tool with other tools, so i have sub agents that are also getting into the infinite loop. So, unfortunately I'm not able to use that one
xuanyang15 commentedon Nov 6, 2025
Confirmed with the model team that there is a regression on supporting structured output + function calling, the model may repeat function calls and doesn't output JSON as final output. The fix is already checked in code and the rollout ETA is Nov 10-11.
In the meantime, you can consider:
set_model_responsefunction to generate the JSON output, not the model.xuanyang15 commentedon Nov 11, 2025
Confirmed with the model team that the fix rollout is done. I have tried the example in #3413 (comment), it works now:
dorz-saymine commentedon Nov 20, 2025
I upgraded to 1.18 and saw this issue.
Using tools with output_schema.
Using gemini 2.5 pro with vertex
Are you sure the fix was rolled out on the model?
xuanyang15 commentedon Nov 20, 2025
@dorz-saymine I double checked with the model team that the fix has been rolled out.
I also tried with both the
weather_agentandSimpleTestAgent, it works for me.However, it is worthy pointing out that the
SimpleTestAgentis actually not well set up, the prompt sent to the LLM could cause some confusion, because the output schema isSimpleResultand the functionsimple_validate's description said it returnsSimpleResult.Model team suggests to avoid above confusion when you define your agent.
@dorz-saymine Could you please try the weather agent in #3413 (comment)?
dorz-saymine commentedon Dec 21, 2025
@xuanyang15 thanks for the reply.
I finally got to version upgrade, and I found the issue, it was an instruction to use "set_model_response" tool that caused the issue.
Now using version 1.21.0 it works well