Autonomous AI agents excel at decomposing high-level objectives into iterative subtasks, but recursive execution without boundaries is one of the quickest ways to drain API token balances. When an agent enters a circular reasoning loop, repeatedly attempts to parse broken web pages, or spawns infinite subtask branches, token costs can spiral within minutes. In AgentGPT (developed by Reworkd), developers and power users manage this risk through two core operational controls: hard execution loop limits and multi-format task output exports.
By establishing strict loop thresholds and token quotas before launching an agent—and extracting structured execution logs before terminating a run—teams can prototype autonomous workflows safely and predictably.
1. How AgentGPT's Recursive Loop Consumes Tokens
To understand why loop limits are critical, consider AgentGPT's core execution flow:
- Goal Ingestion: The agent takes a top-level goal and generates an initial array of subtasks.
- Task Analysis & Execution: The agent selects the first pending subtask, invokes the language model (such as GPT-3.5-Turbo or GPT-4) or external tools, and records the intermediate result.
- Task Creation & Refinement: Based on the result, the agent evaluates whether new subtasks must be added to the queue.
- Recursive Cycle: Steps 2 and 3 repeat continuously until either all subtasks are finished or a hard stop is encountered.
Each pass through this cycle constitutes an execution loop. In a standard run, each loop triggers multiple LLM calls (task analysis, tool execution, and subtask generation), each sending context history that grows with every step. Without explicit safeguards, complex or ambiguous goals can quickly exhaust thousands of tokens per minute.
2. Configuring Execution Loop Limits in the User Interface
AgentGPT provides built-in client-side governance controls located within its settings drawer and configuration pages.
Accessing Advanced Settings
- Open the AgentGPT web interface or your local instance.
- Click the Settings (⚙️) button in the left sidebar or navigate directly to
/settings. - Ensure you are signed in (via GitHub, Google, or Discord) or running a self-hosted instance. In the hosted version, the Advanced Settings section is disabled for unauthenticated guest sessions to protect shared infrastructure.
Configuring the Loop Slider (customMaxLoops)
Under Advanced Settings, locate the Loop configuration parameter:
- Slider Range: Configurable from 1 to 25 loops (step: 1).
- Default Values: The default threshold is preset to 25 loops for standard runs and 10 loops when using a custom API key.
- Operational Impact: The value controls the exact maximum number of task execution cycles the agent can run during a single session.
When the agent reaches this configured cap, execution halts immediately, and the console displays the safety message:
The maximum number of loops have been reached, this agent is shutting down.
(In earlier releases, this was presented as: "To save your wallet, and our infrastructure costs, this agent is shutting down.")
Recommended Loop Budgets by Task Type
- Targeted Summaries & Single-Topic Queries: 3 to 7 loops.
- Multi-Step Content Generation & Comparisons: 8 to 12 loops.
- Deep Web Research & Multi-Source Analysis: 15 to 25 loops.
Complementary Cost Controls in Settings
Loop limits work best when paired with adjacent parameters in the same settings panel:
- Tokens (
maxTokens): Adjust the slider (range: 200 up to the model limit, such as 4,000 tokens) to restrict the maximum output size generated by each individual API call. - Model Selection: Switch between
gpt-3.5-turbo(cost-efficient for general workflows) andgpt-4(reserved for complex logical decomposition). - Temperature: Lower the slider towards
0.0or0.2to make subtask outputs deterministic, minimizing repetitive hallucinations that provoke runaway loops. - Custom API Key: Add your personal OpenAI API key with instant validation via the Test button to manage costs directly against your own billing quota.
3. Real-Time Execution Lifecycle Controls
In addition to static pre-run configuration, AgentGPT provides real-time lifecycle controls directly on the console window:
- Pause Button (
FaPause): Temporarily halts task execution between work items. Pausing lets developers review generated subtasks and current execution logs before deciding whether to proceed. - Play / Resume (
FaPlay): Resumes a paused agent, executing the next task in the queue. - Stop Button (
FaStop): Issues an immediate hard abort (lifecycle: stopped). Any remaining tasks in the queue are cancelled, and active LLM streaming calls are severed to prevent further token expenditure.
Using manual pausing during early testing allows you to verify that the agent's task decomposition makes sense before letting it run autonomously.
4. Self-Hosted Backend and Environment Configuration
For developers hosting AgentGPT locally via Docker or deploying the platform on internal infrastructure, loop limits can be enforced at the backend and source levels.
Backend Environment Variable
AgentGPT's Python backend (reworkd_platform) defines application-wide settings using Pydantic. The platform exposes a dedicated environment variable for the global loop cap:
# In your .env file
REWORKD_PLATFORM_MAX_LOOPS=20
This sets the maximum execution cycles on the server side (settings.max_loops), preventing API clients from exceeding specified limits even if client settings are bypassed.
Modifying Frontend Bounds
Developers who need to expand or tighten the loop slider range can adjust the frontend source files directly:
- In
next/src/pages/settings.tsx, the slider attributes can be altered:<Input label={`${t("LOOP")}`} value={settings.customMaxLoops} name="loop" type="range" onChange={(e) => updateSettings("customMaxLoops", parseFloat(e.target.value))} attributes={{ min: 1, max: 50, // Modified from default 25 step: 1, }} helpText={t("CONTROL_THE_MAXIMUM_NUM_OF_LOOPS")} icon={<FaSyncAlt />} disabled={disableAdvancedSettings} /> - In
next/src/utils/constants.ts, default values can be customized:export const DEFAULT_MAX_LOOPS_FREE = 25 as const; export const DEFAULT_MAX_LOOPS_CUSTOM_API_KEY = 10 as const;
5. Exporting Task Outputs in AgentGPT
Once an agent finishes executing—or when you pause or stop an ongoing run—you need to capture its research results and task logs. AgentGPT offers several export pathways ranging from quick client-side downloads to programmatic data access.
Console Window Export Dropdown
At the top-right corner of the agent console window (MacWindowHeader), click the Export icon (CgExport). This reveals three native export options:
- Copy (Clipboard):
- Extracts the full text content of the active execution list (
element.innerText), including the overarching goal, subtasks created, execution steps, and task responses. - Copies the structured plain text directly into the system clipboard with automatic fallback for older browsers.
- Extracts the full text content of the active execution list (
- Image (PNG):
- Uses the client-side
html-to-imagerendering engine to capture the full scrollable conversation element (element.scrollHeight). - Generates a high-resolution screenshot and downloads it as
agent-gpt-output.png. - Ideal for visual reports, team presentations, or archiving execution history without formatting discrepancies.
- Uses the client-side
- PDF Document:
- Uses
@react-pdf/renderervia the built-inPDFButtoncomponent. - Parses the message stream into discrete sections:
Agent Goal: [goal text]Adding Task: [task name]Executing: "[task name]": [task output and findings]
- Automatically formats and downloads the document as
my-document.pdf, providing a clean, printable summary of the completed work.
- Uses
Platform Bulk & API Exports
For enterprise and scraping-oriented workflows built around the Reworkd platform:
- Bulk Exports: Navigate to
app.reworkd.ai/exportsto download complete CSV or JSON dumps of data gathered across specific agent groups or batch jobs. - Database & Programmatic Extraction: In self-hosted setups, all agent sessions and task states are persisted via SQLAlchemy / Prisma in the database tables
agent_runandagent_task. Developers can run SQL queries or hook into the FastAPI REST endpoints (/api/agent/execute) to pipe structured task outcomes directly into downstream data pipelines.
6. Summary and Best Practices
To maintain budget predictability while leveraging AgentGPT:
- Set Loop Limits First: Always review the
Loopslider under Settings before deploying a goal. Keep the threshold between 5 and 15 loops for exploratory tasks. - Cap Max Tokens: Restrict
maxTokensper call to between 1,000 and 2,000 to prevent verbosity from multiplying total costs across iterative loops. - Monitor Early Iterations: Use the pause and stop controls during the initial 2–3 subtasks to ensure the agent is heading in the desired direction.
- Export Promptly: Download a PDF or copy execution text as soon as the agent reaches its goal or hits the loop cap, ensuring no task outputs are lost when refreshing the session.
(Note: The reworkd/AgentGPT repository was archived in January 2026. Developers running production autonomous workflows on self-hosted forks should maintain their own environment variable safeguards and export pipelines based on these established architectural patterns.)