Skip to content

Agent with output_schema + tools enters infinite loop ADK v1.18.0 #3413

Closed

Description

@tommyhutcheson

** 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()
  1. 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.

Activity

  1. added
    core[Component] This issue is related to the core interface and implementation
    on Nov 5, 2025
  2. added theissue type on Nov 5, 2025
  3. xuanyang15 commented on Nov 6, 2025

    @xuanyang15
    Collaborator

    I can reproduce this issue with the following simplified agent:

    from typing import Any
    
    from google.adk.agents import Agent
    from google.adk.tools import FunctionTool, ToolContext
    from pydantic import BaseModel, Field
    
    
    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
      """
      result = {"status": True, "message": "Validation successful"}
      return result
    
    
    root_agent = Agent(
        name="SimpleTestAgent",
        model="gemini-2.5-pro",
        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. Return the result of the tool call as output.
        """,
        output_schema=SimpleResult,
        output_key="validation_result",
        tools=[FunctionTool(func=simple_validate)],
    )

    I looked in the log, with the follow request to the model:

    {
      "contents": [{
        "role": "user",
        "parts": [{
          "text": "Hi"
        }]
      }, {
        "role": "model",
        "parts": [{
          "functionCall": {
            "name": "simple_validate",
            "args": {
            }
          },
          "thoughtSignature": "CoAHAePx/17m0itjqnIfnM6avs4qBFHVNz/AitYBGm1CwxboSIeonG+kDJjRUtaxmsIi9QYdWoRkFU/HeTLNhmMnlVWNDL+MjdYuDmA+MeFjDsxYrfUuc7NSbVOcUwZRJFynJa0tzzhkP4XNkNdoEfyMJcgcj6ojwXIKrP/aQHeMXEhseF9PXOaKSY9cIiDQIg6wVugzWaMsBOMnZsyMw4bxU9Xj5fAfnJCSIxb7+O6Lj8ILKTA5NJ1JfWde00KW/+Be0DA+I+4q1huEcLBvEsU/Aq26rCyCNHTYNnTN9CoGxEuc5/qOXnWdICZ4jd/yXaoUzO4k0aX6AMJsDHGlCxwgmRp+mf53mRSF6QL6Uy2Zxine/rIQ6E9AGMYytDQbcQiLiNHYbEWsl1vNhRZqRC/HAoHKA9A1Prz7DmETVgB+Q59MatASsnIR8x/6rIBXSA06DQYvI4d3T1y3o0yG9Dtz1Im90Ydx1LDuY3jicJfEkX26OQPqiOBlCpBnjl+/zfEN7jkKgiB/DnhgYdEjce9UuWHzqHYTvccTpIdn35/DtTgo2z49Rk+a9DWlEJ9YrrnN8q8qI5gl3gdvUI5rYGOYvlorV3SvIJ+6KE3O4aOTJr/Rb16kWo++X1Dp87NQSjcleCnZGEZ3qwNIDBo7y4k7XzUin1HAYqMHFICERxkGDRZxXcphuuJwEJoU2suCmo1d5X0dmEJfb0sYC6LEGKzP4lHNd/T9s6Y/ioDW6Rk/gR6UpVFSxAGYnXcyVPl9N8XCdVD6ApWebkkeNHj29UcC8OfuJsm4Rq0qT9I2ZEXsm99i+50TWRZQl+DSlhRutn06PyKhpnl5TAvZjd1CeXdurHDjfpbyAKFSWZpB/Ru1HpMf3cytj+Nhp1942SXWGF8Pad6n2HzOX9eaAjD0wyr/w3psISAUqMr27G8qEyU/GiV0ulMV0SufbqVHClMByJI8dA2EMQ7kc/mIs4UTN1/kUj5p3SfUT946zYMOJquJIm6gH8aSK/YAnEaI53PNXreeLSE4HW8c2gQjNpgVoiMcP9SHD+VIBZRSyteCjvqciOfVlsf9bItrOndM5HiMyYJ/mdruAlynJGFx/Q6TAcP1lZi9yZkYP8OtGVVql9hdx/Zz2dQuWQLptHlHjQz9UnQ0tXQRWWuOB1+LQ/tZ0nMYVQ15gD+yYCbXc3nOHr3cx2U="
        }]
      }, {
        "role": "user",
        "parts": [{
          "functionResponse": {
            "name": "simple_validate",
            "response": {
              "status": true,
              "message": "Validation successful"
            }
          }
        }]
      }],
      "generationConfig": {
        "responseMimeType": "application/json",
        "responseSchema": {
          "type": "OBJECT",
          "properties": {
            "status": {
              "type": "BOOLEAN",
              "description": "Whether the validation was successful",
              "title": "Status"
            },
            "message": {
              "type": "STRING",
              "description": "A message explaining the result",
              "title": "Message"
            }
          },
          "required": ["status", "message"],
          "description": "Simple output schema with just two fields.",
          "title": "SimpleResult",
          "propertyOrdering": ["status", "message"]
        }
      },
      "model": "projects/model-extend-test/locations/us-central1/publishers/google/models/gemini-2.5-pro",
      "tools": [{
        "functionDeclarations": [{
          "name": "simple_validate",
          "description": "A simple validation tool that returns data matching SimpleResult schema.\n\n  Returns:\n      Dict with \u0027status\u0027 (bool) and \u0027message\u0027 (str) fields\n  ",
          "response": {
            "type": "OBJECT"
          }
        }]
      }],
      "systemInstruction": {
        "role": "user",
        "parts": [{
          "text": "You are a simple validation agent.\n\n    **Your task:**\n    1. Call the simple_validate tool ONCE\n    2. Use the tool\u0027s response to create your final output\n    3. DO NOT call the tool more than once\n\n    **Critical:**\n    - After receiving the tool response, produce your final SimpleResult output\n    - The tool returns a dict with \u0027status\u0027 and \u0027message\u0027 fields\n    - Use these values directly in your output\n    \n\nYou are an agent. Your internal name is \"SimpleTestAgent\". The description about you is \"A minimal test agent with output_schema and a tool.\"."
        }]
      },
      "labels": {
        "adk_agent_name": "SimpleTestAgent"
      }
    }
    

    The model returns function again:

    {
      "candidates": [{
        "content": {
          "role": "model",
          "parts": [{
            "functionCall": {
              "name": "simple_validate",
              "args": {
              }
            },
            "thoughtSignature": "CoMFAePx/16GeRLHxMMEqJ4suX7CjyykNlZtfZky4ZC/lwxj5BU2GvXOjXB+SVMdecROhd3dXBNzVZFnWH6oTeyEQo/LYkppuXfwXMkMyA1fWgQHF1THSTSt0KEpVPUPmtK1VLiW/IioR041heo6CimgIVMxTdaUhKNtbSocBTus3unCA2KiEgP3Hc6ltLtwM+F+jafOHz7mOc17cIBCLvH4yZtsnvRZ1diqkSSvbcLeU7cZh/8ZrQ2W/RQ4WM36acSJZ6KM7etbIc/2EoaeDyOxFSqAHo1q0Lda0erD1Hbzw+VnGgUPXs5Tu+RG8IhjOvsn79Vdq7JKiMg4883KsJjYzXSkdde3+rEcsPpqK0i3il7Ncnzg3PSxrGoeWjrP3FB34SEXx8fNo9mFbtfPDqLTk+RBNuy5CqjCG4ATStfsgml3pDECAVJ3QMj3Aydw7Y+7FsKSGHFHi0HBstxe8+V9SowD2DIQcBcfLxL6Kuh5TTJPqlOH5cz+BTca7Hmuhg97Q9+eA0AXImsu99eTbxqf/3ZGy4byZJ4Ub9Riwu2UhnYHf1gnLXJh2PKOYEPTnuug/OQKW9t++ivD8s6Ehg+gNnEWVFpb8WoRslCv9adjx32OboR0+LTTh5nYgeX1XoBDGJFc4YZOjgUCbPuEoxjwEQX/BlIpJRczKS8HYyblJLHtkYbPQQ3JZBVGpFySGiQqW/mvEb3fYL2dgsYHmaMJMTqHUchEgLTjWIGeBsB3Y7rFSgAuiB/QSO38uU59Mixbs40j25wA1ymu3RXhuOLxGV94TM2t5JbMm4zV4bbr8WaiBH9tFQX/MSWExDphZIp+Q1Wx9XouXYXMw4iBlXNYLSGZnA=="
          }]
        },
        "finishReason": "STOP",
        "score": -11.66387939453125,
        "avgLogprobs": -3.8879597981770835
      }],
      "usageMetadata": {
        "promptTokenCount": 216,
        "candidatesTokenCount": 3,
        "totalTokenCount": 366,
        "billablePromptUsage": {
          "textCount": 795
        },
        "trafficType": "ON_DEMAND",
        "promptTokensDetails": [{
          "modality": "TEXT",
          "tokenCount": 416
        }],
        "candidatesTokensDetails": [{
          "modality": "TEXT",
          "tokenCount": 3
        }],
        "thoughtsTokenCount": 147
      },
      "modelVersion": "gemini-2.5-pro",
      "createTime": "2025-11-06T00:24:26.556662Z",
      "responseId": "uuoLafb8IeSLi-8PmN_X-Aw"
    }
    

    It seems that the model doesn't handle function calls correctly.

  4. xuanyang15 commented on Nov 6, 2025

    @xuanyang15
    Collaborator

    @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.

  5. pedrodotavila commented on Nov 6, 2025

    @pedrodotavila

    Hi, I'm having same issue Is there an ETA for this bug?

  6. xuanyang15 commented on Nov 6, 2025

    @xuanyang15
    Collaborator

    @pedrodotavila Could you please share your code?

    I actually tried with a different agent:

    from typing import Any
    
    from google.adk.agents.llm_agent import Agent
    from pydantic import BaseModel, Field
    
    
    class WeatherResult(BaseModel):
      """Weather result schema."""
    
      condition: str = Field(
          description="The weather condition, e.g. sunny, cloudy, etc."
      )
      temperature: int = Field(description="The temperature in Fahrenheit.")
    
    
    def get_weather(city: str) -> dict[str, Any]:
      """Retrieves the current weather report for a specified city.
    
      Args:
          city (str): The name of the city for which to retrieve the weather report.
    
      Returns:
          dict: status and result or error msg.
      """
      if city.lower() == "new york":
        return {
            "status": "success",
            "report": (
                "The weather in New York is sunny with a temperature of 25 degrees"
                " Celsius (77 degrees Fahrenheit)."
            ),
        }
      else:
        return {
            "status": "error",
            "error_message": f"Weather information for '{city}' is not availdable.",
        }
    
    
    root_agent = Agent(
        name="weather_agent",
        model="gemini-2.5-flash",
        description="Agent to answer questions about the weather in a city.",
        instruction=(
            "You are a weather agent. Use the get_weather tool to retrieve the"
            " weather information."
        ),
        tools=[get_weather],
        output_schema=WeatherResult,
        output_key="weather_result",
    )

    It works fine:

    Image
  7. pedrodotavila commented on Nov 6, 2025

    @pedrodotavila
    from google.adk.agents import (LlmAgent,  SequentialAgent)
    from google.adk.tools.agent_tool import AgentTool
    from google.adk.tools import google_search
    from google.genai import types
    from .prompts import WEB_RESEARCH_PROMPT
    from .schemas import AccountResearchOutputs
    
    
    initial_search = LlmAgent(
        name="InitialAccountResearch",
        model="gemini-2.5-flash",
        description="Agent to research customer information.",
        instruction=WEB_RESEARCH_PROMPT,
        tools=[google_search]
    )
    
    account_research_agent = SequentialAgent(
        name="AccountResearchAgent",
        sub_agents=[
            initial_search,
        ],
        description="Orchestrates the workflow to research companies.",
    )
    
    
    account_research_agent_tools = [
        AgentTool(agent=account_research_agent),
    ]
    
    root_agent = LlmAgent(
        name="account_research_agent",
        model="gemini-2.5-pro",
        description="Agent to research",
        instruction=ACCOUNT_RESEARCH_ROOT_INSTRUCTIONS,
        tools=[*account_research_agent_tools],
        output_schema=AccountResearchOutputs,
    )

    I tried to move all my code to this snippet, so maybe some imports aren't working, i cant share the prompts, sorry.

    @xuanyang15

  8. xuanyang15 commented on Nov 6, 2025

    @xuanyang15
    Collaborator

    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.

  9. pedrodotavila commented on Nov 6, 2025

    @pedrodotavila

    @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

  10. xuanyang15 commented on Nov 6, 2025

    @xuanyang15
    Collaborator

    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:

    • Using Gemini API (use GOOGLE_API_KEY=), instead of Vertex API (GOOGLE_GENAI_USE_VERTEXAI=1) to bypass this problem, or
    • Using v1.17.0, where ADK still relies on the extra set_model_response function to generate the JSON output, not the model.
  11. xuanyang15 commented on Nov 11, 2025

    @xuanyang15
    Collaborator

    Confirmed with the model team that the fix rollout is done. I have tried the example in #3413 (comment), it works now:

    Image
  12. self-assigned this
    on Nov 12, 2025
  13. dorz-saymine commented on Nov 20, 2025

    @dorz-saymine

    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?

  14. xuanyang15 commented on Nov 20, 2025

    @xuanyang15
    Collaborator

    @dorz-saymine I double checked with the model team that the fix has been rolled out.

    I also tried with both the weather_agent and SimpleTestAgent, it works for me.

    However, it is worthy pointing out that the SimpleTestAgent is actually not well set up, the prompt sent to the LLM could cause some confusion, because the output schema is SimpleResult and the function simple_validate's description said it returns SimpleResult.

    Model team suggests to avoid above confusion when you define your agent.

    @dorz-saymine Could you please try the weather agent in #3413 (comment)?

  15. dorz-saymine commented on Dec 21, 2025

    @dorz-saymine

    @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

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

Metadata

Metadata

Labels

core[Component] This issue is related to the core interface and implementation

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions