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

[FEATURE] Add configurable limits for cycles, token counts, and overall runtime

Open timsee opened this issue 1 year ago • 8 comments

Problem Statement

For our use case, we want to be able to set limits to handle when the agent is stuck in a loop/when the task is more complex than anticipated. This is to address a concern with the potential costs of letting the agent dictate how much compute it needs.

With Callback Handlers we can see the information we need with this toy example for max_cycles:

import functools
from strands import Agent

def _callback_handler(max_cycles, **kwargs):
    if "event_loop_metrics" in kwargs:
        event_loop_metrics = kwargs["event_loop_metrics"]
        if event_loop_metrics.cycle_count > max_cycles:
            logger.warning(
                f"TODO: end run, cycle budget exhausted: {event_loop_metrics.cycle_count} > {max_cycles}"
            )

_handler = functools.partial(_callback_handler, max_cycles=100)
agent = Agent(model=model, callback_handler=_handler)

But once we have this information, there is currently no way to act on it.

Proposed Solution

The ideal state for this feature would be that you can pass a limits object at the time of constructing the agent and have the agent handle it:

from pydantic import BaseModel

class AgentLimits(BaseModel):
      token_budget: int
      cycle_budget: int
      runtime: float # in seconds
   
budget = AgentLimits(token_budget=10000, cycle_budget=100, runtime=1800)
agent = Agent(model=model, callback_handler=_handler limits=budget)

OR,

Provide hooks that we can implement to catch these updates and exit out gracefully.

Use Case

  • As a user, I have a limited bedrock budget, and want to make sure my agent doesn't exceed my allocation.
  • As a user, I want to cancel out an agent workflow if it takes more than 10 minutes.

Alternatives Solutions

No response

Additional Context

No response

timsee avatar Jun 09 '25 16:06 timsee

+1 An alternate (simpler?) solution could be to add a recursion_limit type of parameter that LangGraph has to prevent runaway agents and control costs. This would provide developers with fine-grained control over agent execution and prevent runaway scenarios.

Implementation Details

1. Add parameter to Agent class

Modify the Agent class constructor in /src/strands/agent/agent.py around line 179:

def __init__(
    self,
    tools: Optional[List[Tool]] = None,
    model: Optional[Union[str, Model]] = None,
    system_prompt: Optional[str] = None,
    callback_handler: Optional[Callable] = None,
    max_parallel_tools: int = 1,
    recursion_limit: int = 25,  # Add this parameter
    **kwargs: Any,
):
    # ... existing initialization code ...
    self.recursion_limit = recursion_limit

2. Update event_loop_cycle function

Modify the event_loop_cycle function in /src/strands/event_loop/event_loop.py around line 36:

def event_loop_cycle(
    model: Model,
    system_prompt: Optional[str],
    messages: Messages,
    tool_config: Optional[ToolConfig],
    callback_handler: Any,
    tool_handler: Optional[ToolHandler],
    tool_execution_handler: Optional[ParallelToolExecutorInterface] = None,
    recursion_limit: int = 25,  # Add this parameter
    current_recursion_depth: int = 0,  # Track current depth
    **kwargs: Any,
) -> Tuple[StopReason, Message, EventLoopMetrics, Any]:

3. Proposed Implementation Logic

def event_loop_cycle(
    model: Model,
    system_prompt: Optional[str],
    messages: Messages,
    tool_config: Optional[ToolConfig],
    callback_handler: Any,
    tool_handler: Optional[ToolHandler],
    tool_execution_handler: Optional[ParallelToolExecutorInterface] = None,
    recursion_limit: int = 25,
    current_recursion_depth: int = 0,
    **kwargs: Any,
) -> Tuple[StopReason, Message, EventLoopMetrics, Any]:
    
    # Check recursion limit before processing
    if current_recursion_depth >= recursion_limit:
        error_msg = f"Maximum recursion limit ({recursion_limit}) exceeded. Agent stopped to prevent runaway execution."
        
        # Create an error message to return
        error_message = Message(
            role="assistant",
            content=error_msg
        )
        
        # Return with appropriate stop reason
        return (
            StopReason.MAX_RECURSION_REACHED,  # New stop reason
            error_message,
            EventLoopMetrics(),  # Empty metrics
            None
        )
    
    # ... existing event loop logic ...
    
    # When making recursive calls (e.g., when tools are used):
    if tool_use_requests:
        # ... tool execution logic ...
        
        # Recursive call with incremented depth
        return event_loop_cycle(
            model=model,
            system_prompt=system_prompt,
            messages=updated_messages,
            tool_config=tool_config,
            callback_handler=callback_handler,
            tool_handler=tool_handler,
            tool_execution_handler=tool_execution_handler,
            recursion_limit=recursion_limit,
            current_recursion_depth=current_recursion_depth + 1,  # Increment depth
            **kwargs
        )

4. Add new StopReason

Update the StopReason enum to include:

class StopReason(Enum):
    # ... existing reasons ...
    MAX_RECURSION_REACHED = "max_recursion_reached"

Usage Example

from strands import Agent
from strands_tools import calculator

# Create agent with custom recursion limit
agent = Agent(
    tools=[calculator],
    recursion_limit=10  # Limit to 10 recursive calls
)

# Agent will stop after 10 iterations to prevent runaway costs
result = agent("Perform a complex calculation that might require multiple steps")

This feature would significantly improve the production readiness of the Strands Agents SDK by providing essential cost control and safety mechanisms.

aarora79 avatar Jul 08 '25 13:07 aarora79

We're currently leaning towards hooks (#231) as being a general-purpose/extensible way of implementing event limits.

We've recently added the core system of hooks which allows you to observe a subset of events within the event-loop and while we don't currently have a way to force an exit from the event-loop, it's something we'd like to do to enable limiters to be built on-top-of-hooks. Technically you could use an exception to exit eagerly however.

The documentation is currently pending release, but was added via strands-agents/docs/pull/130

zastrowm avatar Jul 11 '25 14:07 zastrowm

The first draft of hooks has now been released via #231

There's a couple of additional follow-ups needed:

  • We need to determine how we want limits to be enforced (is it an exception of r a new stop mode?
  • We need the event_loop to allow hooks to exit the event loop via the mechanism of ^

zastrowm avatar Jul 22 '25 18:07 zastrowm

any solution to limit the cycles as of today?

iker592 avatar Oct 14 '25 18:10 iker592

+1 Additionally, I can think of another use case: on-demand stopping of an agent (i.e. cancel a running prompt). Sometimes it's not a matter of budget, it can simple be a user that would like to cancel a running prompt for whatever reason. In this case, we need to stop the agent, and clean up stale state. It would be great to have a clean way to do that.

omeraha avatar Oct 17 '25 16:10 omeraha

+1 On this. We recently ran into a scenario with an Orchestrator Agent calling additional agents as tools and open asking a question that should be nonsensical "Give me HSL values for indigo pink" it attempted to search the internet indefinitely. In this case it seems the only configuration of something like max_iterations resides with the Swarm() declaration, though this would likely be useful on an individual Agent basis. For example, you could either declare max_iterations at the top level agent or constrain it more granularly for specific agents called as tools.

ctoh-skechers avatar Dec 15 '25 22:12 ctoh-skechers

https://github.com/horizon-rl/strands-sglang/blob/main/src/strands_sglang/tool_limiter.py is an implementation of a tool_limiter that uses hooks to implement tool limits

zastrowm avatar Jan 08 '26 14:01 zastrowm

Thanks for the use cases and ideas shared here. In Python, invoke and stream now accept limits (turns, output_tokens, total_tokens); reaching one ends the run with a limit_* stop reason instead of raising. This shipped in python/v1.42.0; see Cap the work one call can do. For time-based stopping, use agent.cancel() (Stop a running agent). If something is still missing, please open a new issue.

yonib05 avatar Oct 25 '26 23:10 yonib05