crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] Agent loop is not stopped after max iterations reached

Open ehansis opened this issue 1 year ago • 2 comments

Hello all,

It seems to me like the agent loop is not being stopped once max_iter has been reached. handle_max_iterations_exceeded is called and a formatted answer is prepared, but this answer is being overwritten in following LLM calls and the loop is not stopped.

https://github.com/crewAIInc/crewAI/blob/e4cc9a664c1e2db535374640303ca535b23e3dae/lib/crewai/src/crewai/agents/crew_agent_executor.py#L208

A previous revision had a break right after preparing the formatted answer, but this was lost in rev efe27bd.

... or am I missing something here?

Cheers!

ehansis avatar Nov 06 '25 14:11 ehansis

thanks for flagging this @ehansis, we've been tracking internally. I'll tag this issue in a pr.

greysonlalonde avatar Nov 06 '25 15:11 greysonlalonde

I've run into this specifically with CrewAI agents when the task description is slightly ambiguous—the LLM sometimes ignores the framework's hard stop signal because it thinks it's "just one step away" from the answer, causing it to override the iteration limit or hallucinate a new step.

Before digging into the CrewAI internals, it helps to verify if the agent's system prompt/role definition itself is prone to circular logic (semantic loops) independent of the framework.

I built a lightweight middleware API to stress-test agent prompts against this exact kind of loop injection. You can run your agent's role and goal through it to see if the logic is robust enough to handle forced repetition:

import requests

# Paste your CrewAI Agent's Role/Goal here
agent_role = "Senior Researcher"
agent_goal = "Uncover groundbreaking technologies in AI"
combined_prompt = f"Role: {agent_role}. Goal: {agent_goal}."

print("🚀 Running Loop Susceptibility Test...")

response = requests.post(
    "[https://agentic-qa-api.onrender.com/docs](https://agentic-qa-api.onrender.com/docs)",
    json={
        "system_prompt": combined_prompt,
        "attack_type": "Loop Injection", 
        "client_name": "CrewAI_Issue_3847"
    }
)

result = response.json()
print(f"Status: {result['status']}")

if 'full_log' in result:
    # If the tool successfully forces a loop, your prompt needs tighter constraints
    print(f"Logs: {result['full_log']}")

Saurabh0377 avatar Nov 25 '25 17:11 Saurabh0377