Skip to content

Conversation

@jayy-77
Copy link

@jayy-77 jayy-77 commented Jan 17, 2026

…Y' (Issue #4179)

This commit fixes the infinite loop bug where agents with FunctionCallingConfig mode='ANY' could continuously call tools without ever providing a final response, causing the agent to hang indefinitely.

Fixes #4179

Please ensure you have read the contribution guide before creating a pull request.

Link to Issue or Description of Change

1. Link to an existing issue (if applicable):

…Y' (Issue google#4179)

This commit fixes the infinite loop bug where agents with FunctionCallingConfig
mode='ANY' could continuously call tools without ever providing a final response,
causing the agent to hang indefinitely.

## Root Cause
When using FunctionCallingConfig with mode='ANY', the LLM is free to keep calling
tools as many times as it wants. However, there was no mechanism to prevent infinite
loops where the model never provides a final response and keeps calling tools.

## Solution
Added a new 'max_tool_iterations' configuration parameter with the following features:

1. **New Configuration (run_config.py)**:
   - Added 'max_tool_iterations' field with default value of 50
   - Prevents infinite loops by limiting consecutive tool-calling cycles
   - Can be disabled by setting to 0 or negative values
   - Includes validator with warning for disabled limit

2. **Iteration Tracking (invocation_context.py)**:
   - Added 'ToolIterationsLimitExceededError' exception
   - Extended '_InvocationCostManager' to track tool iterations
   - Added 'increment_tool_iteration_count()' method
   - Added 'reset_tool_iteration_count()' method
   - Counter resets when agent provides final response (no function calls)

3. **Flow Integration (base_llm_flow.py)**:
   - Integrated counter increment when function calls are detected
   - Integrated counter reset when final response is received
   - Applied to both 'run_async' and 'run_live' flows

## Changes Made
**Modified Files:**
- src/google/adk/agents/run_config.py (added max_tool_iterations config)
- src/google/adk/agents/invocation_context.py (added iteration tracking)
- src/google/adk/flows/llm_flows/base_llm_flow.py (integrated counter logic)

**New Files:**
- tests/unittests/flows/llm_flows/test_tool_iteration_limit.py (comprehensive tests)

## Testing
Added comprehensive unit tests covering:
- Default configuration value
- Limit enforcement
- Counter reset behavior
- Disabled limit scenario
- Configuration validator

All tests pass successfully.

## Impact
This change prevents infinite loops when using FunctionCallingConfig mode='ANY',
especially in scenarios like sub-agents being used as tools, where the agent
could previously get stuck in an endless tool-calling cycle.

Fixes google#4179
@google-cla
Copy link

google-cla bot commented Jan 17, 2026

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @jayy-77, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical issue where agents using FunctionCallingConfig with mode='ANY' could enter infinite loops by continuously calling tools without ever producing a final response. The solution introduces a configurable max_tool_iterations limit, ensuring that agents terminate gracefully if they exceed a set number of consecutive tool calls. This enhancement significantly improves the stability and reliability of agent interactions, particularly in complex scenarios involving sub-agents.

Highlights

  • New Configuration Parameter: Introduced max_tool_iterations in RunConfig with a default value of 50 to limit consecutive tool-calling cycles. This parameter can be disabled by setting it to 0 or a negative value, with a validator warning for such cases.
  • Tool Iteration Tracking: Added _number_of_tool_iterations to _InvocationCostManager and new methods (increment_and_enforce_tool_iterations_limit, reset_tool_iterations_counter) to track and enforce the tool iteration limit. A ToolIterationsLimitExceededError is raised if the limit is surpassed.
  • Flow Integration: Integrated the tool iteration counter logic into base_llm_flow.py for both run_async and run_live flows. The counter increments when function calls are detected and resets when the agent provides a final response (no function calls).
  • Comprehensive Unit Tests: Added a new test file test_tool_iteration_limit.py with comprehensive unit tests covering default configuration, limit enforcement, counter reset behavior, disabled limit scenarios, and configuration validation.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@adk-bot adk-bot added the core [Component] This issue is related to the core interface and implementation label Jan 17, 2026
@adk-bot
Copy link
Collaborator

adk-bot commented Jan 17, 2026

Response from ADK Triaging Agent

Hello @jayy-77, thank you for your contribution!

It looks like the Contributor License Agreement (CLA) check has failed. Please make sure you have signed the CLA at https://cla.developers.google.com/.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a robust mechanism to prevent infinite tool-calling loops by adding a max_tool_iterations configuration. The implementation is well-structured across run_config.py, invocation_context.py, and base_llm_flow.py. The new configuration is properly validated, and the iteration counter is correctly managed within the LLM flow. The addition of comprehensive unit tests is excellent and covers the core logic of the new feature. I have one suggestion to improve the validator test to make it more robust. Overall, this is a solid contribution that addresses a critical bug.

Comment on lines +100 to +113
async def test_max_tool_iterations_validator():
"""Test that RunConfig validator warns about disabled limit."""
import logging
import warnings

# Setting to 0 should trigger a warning
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
run_config = RunConfig(max_tool_iterations=0)
assert run_config.max_tool_iterations == 0

# Setting to positive value should not raise
run_config = RunConfig(max_tool_iterations=50)
assert run_config.max_tool_iterations == 50
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation of test_max_tool_iterations_validator does not correctly test for the warning message. The validator uses logger.warning, which is not captured by warnings.catch_warnings by default. To properly test that the warning is logged, you should use the caplog fixture provided by pytest. This will ensure the test is robust and correctly verifies the validator's behavior.

Suggested change
async def test_max_tool_iterations_validator():
"""Test that RunConfig validator warns about disabled limit."""
import logging
import warnings
# Setting to 0 should trigger a warning
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
run_config = RunConfig(max_tool_iterations=0)
assert run_config.max_tool_iterations == 0
# Setting to positive value should not raise
run_config = RunConfig(max_tool_iterations=50)
assert run_config.max_tool_iterations == 50
async def test_max_tool_iterations_validator(caplog):
"""Test that RunConfig validator warns about disabled limit."""
import logging
# Setting to 0 should trigger a warning
with caplog.at_level(logging.WARNING):
run_config = RunConfig(max_tool_iterations=0)
assert run_config.max_tool_iterations == 0
assert 'max_tool_iterations is less than or equal to 0' in caplog.text
# Setting to positive value should not raise or log a warning
caplog.clear()
run_config = RunConfig(max_tool_iterations=50)
assert run_config.max_tool_iterations == 50
assert not caplog.text

@ryanaiagent ryanaiagent self-assigned this Jan 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FunctionCallingConfig(mode="ANY") causes infinite tool-calling loop when sub-agent is used as a tool (google-adk 1.21.0)

3 participants