Heuristic:AIPexStudio AIPex MaxTurns Bound
| Knowledge Sources | |
|---|---|
| Domains | Agent_Safety, Optimization |
| Last Updated | 2026-10-24 12:00 GMT |
Overview
Default `maxTurns=2000` prevents unbounded agent loops from consuming excessive LLM API calls and tokens when a tool repeatedly fails or the agent cannot converge on a solution.
Description
The AIPex agent class caps the number of execution turns per chat invocation at 2000 by default. This is passed to the `@openai/agents` runner as the `maxTurns` parameter. Each "turn" represents one model call followed by any tool calls the model requests. Without this bound, a misconfigured tool or an agent stuck in a retry loop could issue hundreds of API calls indefinitely, incurring substantial cost and never returning a response to the user.
Usage
Use this heuristic when configuring agent execution for production deployments. The default of 2000 turns is generous enough for complex multi-step browser automation tasks while providing a hard safety net. For simpler tasks or cost-sensitive environments, consider lowering the value (e.g., 50-100) to fail fast on runaway loops.
The Insight (Rule of Thumb)
- Action: Set `maxTurns` in `AIPexOptions` when creating an agent instance.
- Value: Default is `2000`. Lower to `50-100` for simple tasks; raise only if you have explicit need for very long multi-tool workflows.
- Trade-off: A higher value allows longer autonomous workflows but risks unbounded cost on runaway loops. A lower value fails faster but may interrupt legitimate complex tasks.
- Compatibility: Works with all model providers; the runner enforces the limit at the `@openai/agents` level.
Reasoning
The agent execution loop calls `run(this.agent, input, { maxTurns: this.maxTurns, ... })`. Each turn includes a model API call (which costs tokens) plus any tool executions. In browser automation scenarios, a tool that consistently fails (e.g., element not found on a dynamic page) can cause the agent to retry indefinitely. The `maxTurns` bound ensures the agent terminates after a finite number of attempts, returning a partial result or error rather than consuming unbounded resources.
Code Evidence
Default maxTurns initialization from `packages/core/src/agent/aipex.ts:37-51`:
private maxTurns: number;
private constructor(
agent: OpenAIAgent,
conversationManager?: ConversationManager,
contextManager?: ContextManager,
maxTurns?: number,
plugins: AgentPlugin[] = [],
) {
this.maxTurns = maxTurns ?? 2000;
}
maxTurns passed to the runner from `packages/core/src/agent/aipex.ts:141-152`:
const result = await run(this.agent, input, {
maxTurns: this.maxTurns,
session: runSession,
stream: true,
});
maxTurns exposed in metrics from `packages/core/src/agent/aipex.ts:113`:
maxTurns: this.maxTurns,