Skip to main content
Autonomous loops let agents work iteratively on complex tasks, automatically stopping when they signal completion or reach limits.

Quick Start

from praisonaiagents import Agent

agent = Agent(
    name="builder",
    instructions="Build the requested feature",
    autonomy=True
)

result = agent.run_autonomous(
    "Create a REST API with user authentication",
    max_iterations=10
)

print(f"Success: {result.success}")
print(f"Iterations: {result.iterations}")

How It Works

Key Features

Completion Promise

Agent signals “done” with a promise tag containing TEXT

Context Clearing

Fresh memory each iteration forces file-based state

Doom Loop Detection

Automatically stops on repeated identical actions

Iteration Limits

Prevents runaway execution with configurable max

Configuration

AutonomyConfig Options

OptionTypeDefaultDescription
max_iterationsint20Maximum loop iterations
completion_promisestrNoneText to detect in promise tags
clear_contextboolFalseClear chat history between iterations
doom_loop_thresholdint3Repeated actions before stopping

Using Config Dict

agent = Agent(
    name="worker",
    instructions="Complete the task",
    autonomy={
        "max_iterations": 30,
        "completion_promise": "FINISHED",
        "clear_context": True,
        "doom_loop_threshold": 5
    }
)

CLI Usage

praisonai loop "Build a REST API" -n 5

CLI Options

FlagDescription
-n, --max-iterationsMaximum iterations (default: 10)
-p, --completion-promisePromise text to signal completion
-c, --clear-contextClear chat history between iterations
-t, --timeoutTimeout in seconds
-m, --modelLLM model to use
-v, --verboseShow verbose output

Result Object

result = agent.run_autonomous(prompt, ...)

# Available fields
result.success          # bool - Task completed successfully
result.output           # str - Final response
result.completion_reason # str - "promise", "goal", "max_iterations", "doom_loop", "timeout", "error"
result.iterations       # int - Number of iterations executed
result.duration_seconds # float - Total execution time
result.started_at       # str - ISO 8601 timestamp when execution started
result.actions          # list - Actions taken each iteration
result.error            # str | None - Error message if failed

Completion Reasons

Agent output contained a promise tag with TEXT matching the configured promise.
Agent output contained completion keywords like “task completed” or “done”.
Reached the maximum iteration limit without completion signal.
Detected repeated identical actions (agent stuck in a loop).
Execution exceeded the configured timeout.
An error occurred during execution.

Best Practices

1

Use Completion Promises

Always set a completion_promise for reliable termination instead of relying on keyword detection.
2

Enable Context Clearing for Long Tasks

Use clear_context=True for tasks that should rely on file state rather than conversation memory.
3

Set Reasonable Limits

Configure max_iterations based on task complexity. Start low and increase if needed.
4

Include Promise in Instructions

Tell the agent to output the promise tag when done:
instructions="When finished, output DONE in a promise tag"

Async Execution

Run autonomous loops asynchronously for concurrent agent execution:
import asyncio
from praisonaiagents import Agent

async def main():
    agent = Agent(
        name="async_worker",
        instructions="Complete the task. Output <promise>DONE</promise> when finished.",
        autonomy=True
    )
    
    result = await agent.run_autonomous_async(
        "Build a calculator",
        completion_promise="DONE",
        max_iterations=10
    )
    
    print(f"Success: {result.success}")
    print(f"Started: {result.started_at}")

asyncio.run(main())
run_autonomous_async() uses achat() internally for non-blocking I/O, enabling true concurrent execution of multiple agents.

Example: Self-Improving Code

from praisonaiagents import Agent

agent = Agent(
    name="improver",
    instructions="""You are a code improvement agent.
    
    1. Read the current code
    2. Identify one improvement
    3. Make the change
    4. Verify it works
    5. If no more improvements needed, output <promise>OPTIMIZED</promise>
    """,
    autonomy=True,
    tools=[read_file, write_file, run_tests]
)

result = agent.run_autonomous(
    "Optimize the performance of src/utils.py",
    completion_promise="OPTIMIZED",
    clear_context=True,
    max_iterations=10
)

if result.success:
    print(f"Code optimized in {result.iterations} iterations")
    print(f"Started: {result.started_at}")
else:
    print(f"Stopped: {result.completion_reason}")