How to limit agent iterations in python
Quick answer
To limit agent iterations in Python, set a maximum iteration count in your agent's control loop or use built-in parameters like
max_iterations if supported by your agent framework. This prevents infinite loops and controls resource usage effectively.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the openai Python package and set your API key as an environment variable to authenticate requests.
pip install openai Step by step
Use a loop with a counter to limit the number of iterations your agent runs. Below is a simple example using OpenAI's gpt-4o model to simulate an agent that stops after 3 iterations.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
max_iterations = 3
iteration = 0
while iteration < max_iterations:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": f"Iteration {iteration + 1}: Say hello!"}]
)
print(response.choices[0].message.content)
iteration += 1 output
Hello! Hello! Hello!
Common variations
You can limit iterations asynchronously or use agent frameworks like LangChain that support max_iterations parameters directly. For example, LangChain agents accept max_iterations to stop automatically.
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, Tool
llm = ChatOpenAI(model_name="gpt-4o", temperature=0)
tools = [Tool(name="Echo", func=lambda x: x, description="Echo input")]
agent = initialize_agent(tools, llm, max_iterations=2, agent_type="zero-shot-react-description")
result = agent.run("Say hello twice")
print(result) output
Hello! Hello!
Troubleshooting
If your agent runs indefinitely, ensure your iteration limit variable is correctly incremented and checked. In frameworks, verify you pass max_iterations correctly and update to the latest SDK version.
Key Takeaways
- Use a loop counter or
max_iterationsparameter to limit agent runs. - LangChain and similar frameworks support built-in iteration limits for agents.
- Always increment and check your iteration variable to avoid infinite loops.