> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Autonomy

> Enable agents to operate independently with doom-loop protection and safety controls

Autonomy lets agents operate independently — detecting doom loops, escalating when stuck, and optionally running in a full-auto iterative mode.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="Assistant",
    instructions="You are an autonomous coding assistant.",
    autonomy=True,
)

agent.start("Refactor the authentication module to use JWT tokens.")
```

The user delegates a coding task; the agent works independently, detects doom loops, and escalates to a human when stuck.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Autonomy Flow"
        Task[📋 Task] --> Execute[⚙️ Execute]
        Execute --> Check{🔍 Doom Loop?}
        Check -->|No| Progress[✅ Progress]
        Check -->|Yes| Escalate[🚨 Escalate]
        Progress --> Complete[🎉 Complete]
        Escalate --> Human[👤 Human Input]
    end

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef process fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff

    class Task input
    class Execute,Check process
    class Progress,Escalate,Complete,Human output
```

## Quick Start

<Steps>
  <Step title="Level 1 — Bool (simplest)">
    Turn on autonomy with a single flag — defaults to the safe `suggest` level.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent

    agent = Agent(
        name="Coder",
        instructions="You are an autonomous task-completion agent.",
        autonomy=True,
    )
    agent.start("Write and test a Python function to merge sorted arrays.")
    ```
  </Step>

  <Step title="Level 2 — String (pick a level)">
    Pass a level name to unlock more independence.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent

    agent = Agent(
        name="Coder",
        instructions="You are an autonomous coding agent.",
        autonomy="full_auto",
    )
    agent.start("Build a REST API endpoint for user authentication.")
    ```
  </Step>

  <Step title="Level 3 — Config class (full control)">
    Use `AutonomyConfig` to tune iteration caps, doom-loop detection, and escalation.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, AutonomyConfig

    agent = Agent(
        name="Coder",
        instructions="You are a precise autonomous agent.",
        autonomy=AutonomyConfig(
            level="auto_edit",
            max_iterations=30,
            doom_loop_threshold=5,
            auto_escalate=True,
        ),
    )
    agent.start("Review and improve the test coverage for the payment module.")
    ```
  </Step>
</Steps>

***

## Autonomy Levels

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    Q{How much autonomy?}
    Q -->|Suggestions only| Suggest[suggest\ndefault — propose changes, user approves]
    Q -->|Auto-edit files| AutoEdit[auto_edit\ncan edit files automatically]
    Q -->|Full autonomous loop| FullAuto[full_auto\niterative loop with completion detection]

    classDef decision fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef level fill:#6366F1,stroke:#7C90A0,color:#fff

    class Q decision
    class Suggest,AutoEdit,FullAuto level
```

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Autonomy
    participant Safety

    User->>Agent: task
    loop Autonomy iterations
        Agent->>Autonomy: Execute step
        Autonomy->>Safety: Doom loop check
        alt Doom loop detected
            Safety-->>Agent: Escalate to user
            Agent-->>User: Request clarification
        else No doom loop
            Autonomy-->>Agent: Continue
        end
    end
    Agent-->>User: Task complete
```

| Phase           | What happens                                              |
| --------------- | --------------------------------------------------------- |
| 1. Execute      | Agent takes action toward the goal                        |
| 2. Safety check | Doom loop tracker monitors for repeated identical actions |
| 3. Escalate     | If stuck, agent asks user for guidance instead of looping |
| 4. Complete     | Iterative mode detects task completion signal             |

### Completion Signals

The loop can stop on several signals — ranked by how reliably they mean "really done".

| Completion Signal           | How It Works                                                         | Reliability                                    |
| --------------------------- | -------------------------------------------------------------------- | ---------------------------------------------- |
| **Goal judge** (`run_goal`) | Independent judge evaluates acceptance criteria after each iteration | ⭐⭐⭐⭐ Most reliable — explicit contract         |
| Tool completion             | Model stops calling tools after a substantive response               | ⭐⭐⭐ Good for tool-driven tasks                 |
| Completion promise          | Model emits the configured `completion_promise` signal text          | ⭐⭐ Depends on the model following instructions |
| Keyword heuristic           | Words like "done"/"finished" or 2 no-tool turns                      | ⭐ Prone to false positives                     |

<Tip>
  When you have a real acceptance criterion for "done" (e.g. "a PR exists"), use [`agent.run_goal(...)`](/docs/features/goal-loop) instead of the heuristics — it gates completion on an independent judge instead of guessing from keywords.
</Tip>

***

## Configuration Options

<Card icon="code" href="/docs/sdk/reference/python/AutonomyConfig">
  Full list of options, types, and defaults — `AutonomyConfig`
</Card>

The most common options at a glance:

| Option                | Type            | Default     | Description                                                      |
| --------------------- | --------------- | ----------- | ---------------------------------------------------------------- |
| `level`               | `str`           | `"suggest"` | `"suggest"`, `"auto_edit"`, or `"full_auto"`                     |
| `max_iterations`      | `int`           | `20`        | Max iterations before stopping                                   |
| `doom_loop_threshold` | `int`           | `3`         | Repeated actions before doom loop detection                      |
| `auto_escalate`       | `bool`          | `True`      | Automatically escalate when stuck                                |
| `completion_promise`  | `str \| None`   | `None`      | Signal text that marks task completion                           |
| `max_budget_usd`      | `float \| None` | `None`      | Cumulative USD spend cap for the run. `None` = unlimited         |
| `max_tokens`          | `int \| None`   | `None`      | Cumulative token cap (input + output). `None` = unlimited        |
| `budget_action`       | `str`           | `"pause"`   | `"pause"` (recoverable) or `"stop"` (terminal) when a cap is hit |

<Note>
  **Safety controls belong together.** `max_iterations` and `doom_loop_threshold` cap *how long* an agent runs; `max_budget_usd` and `max_tokens` cap *how much it spends*. Set both when running unattended — see [Autonomy Budget](/docs/features/autonomy-budget) for the spend/token kill-switch.
</Note>

***

## Common Patterns

### Pattern 1 — Auto-edit mode for coding tasks

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, AutonomyConfig

agent = Agent(
    instructions="You are a senior software engineer.",
    autonomy=AutonomyConfig(
        level="auto_edit",
        max_iterations=15,
        doom_loop_threshold=3,
    ),
)
response = agent.start("Add input validation to all API endpoints in the users module.")
print(response)
```

### Pattern 2 — Full-auto iterative mode

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, AutonomyConfig

agent = Agent(
    instructions="You are an autonomous DevOps agent.",
    autonomy=AutonomyConfig(
        level="full_auto",
        completion_promise="DEPLOYMENT_COMPLETE",
        max_iterations=50,
    ),
)
agent.start("Deploy the application to staging and run smoke tests.")
```

### Pattern 3 — Budget-bounded autonomous runs

Cap an unattended run by money or tokens so it can't burn dollars silently.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, AutonomyConfig

agent = Agent(
    instructions="You are an autonomous research agent.",
    autonomy=AutonomyConfig(
        level="full_auto",
        max_iterations=50,
        max_budget_usd=2.00,     # stop if this run crosses $2
        max_tokens=500_000,      # or 500k tokens, whichever trips first
        budget_action="pause",   # keep the partial result so we can resume
    ),
)

result = agent.run_autonomous("Research and summarise recent LLM safety papers.")

if result.completion_reason == "budget_exhausted":
    print(f"Paused at ${result.metadata['spend_usd']:.2f}")
    print("Partial output:", result.output)
```

Caps are measured from a loop-start baseline, so reusing the same agent across runs never carries prior spend into a new run's cap.

***

## Choosing a Cap

Pick the cap that matches what you care about most for the run.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    Q{What bounds this run?}
    Q -->|Turns matter most| Iter[max_iterations]
    Q -->|Money matters most| Usd[max_budget_usd]
    Q -->|Tokens matter most| Tok[max_tokens]
    Q -->|Should it be recoverable?| Pause{budget_action}
    Pause -->|Resume later| PauseVal["pause"]
    Pause -->|Terminal| StopVal["stop"]

    classDef decision fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef option fill:#6366F1,stroke:#7C90A0,color:#fff

    class Q,Pause decision
    class Iter,Usd,Tok,PauseVal,StopVal option
```

***

## Handling `budget_exhausted`

When a cap trips, the run stops with `completion_reason="budget_exhausted"` and a `metadata` payload describing the spend.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Budget

    User->>Agent: run_autonomous("task")
    loop Each iteration
        Agent->>Budget: check spend vs cap
        alt Under cap
            Budget-->>Agent: continue
        else Cap exceeded
            Budget-->>Agent: budget_exhausted
            Agent-->>User: AutonomyResult(status="paused", metadata={...})
        end
    end
```

The `metadata` dict carries the actual spend, the configured caps, and the status:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
result = agent.run_autonomous("...")

if result.completion_reason == "budget_exhausted":
    print("Status:", result.metadata["status"])       # "paused" or "stopped"
    print("Spent USD:", result.metadata["spend_usd"])
    print("Spent tokens:", result.metadata["tokens"])
    print("Partial output so far:", result.output)

    # Pause is recoverable — raise the cap and re-run:
    agent.autonomy_config["max_budget_usd"] = 5.0
    result = agent.run_autonomous("...")
```

| Key              | Type            | Description                                        |
| ---------------- | --------------- | -------------------------------------------------- |
| `spend_usd`      | `float`         | Actual USD spent this run (baseline-adjusted)      |
| `tokens`         | `int`           | Actual tokens spent this run                       |
| `max_budget_usd` | `float \| None` | The configured USD cap                             |
| `max_tokens`     | `int \| None`   | The configured token cap                           |
| `status`         | `str`           | `"paused"` (recoverable) or `"stopped"` (terminal) |

<Note>
  `budget_action="pause"` returns `status="paused"` and preserves the partial `output` so you can raise the cap and continue. `budget_action="stop"` returns `status="stopped"` — the run is killed unconditionally.
</Note>

***

## Best Practices

<AccordionGroup>
  <Accordion title="Start with suggest level">
    Start with `autonomy=True` (level `suggest`) to see what the agent proposes before giving it permission to edit files or run in a full loop. Graduate to `auto_edit` or `full_auto` when you trust the agent's behavior.
  </Accordion>

  <Accordion title="Set doom_loop_threshold conservatively">
    The default threshold of 3 means 3 identical actions trigger escalation. Lower this to 2 for high-stakes tasks, or raise it to 5 for tasks where retrying the same action is expected behavior (like polling).
  </Accordion>

  <Accordion title="Use completion_promise for iterative mode">
    In `full_auto` mode, the agent loops until it detects completion. Set `completion_promise="TASK_COMPLETE"` and instruct the agent to output this signal when done, giving you clean loop termination.
  </Accordion>

  <Accordion title="Cap unattended runs with max_budget_usd">
    For `full_auto` mode running unattended (nightly jobs, background workers), set `max_budget_usd` as a hard ceiling. Combine with `budget_action="pause"` so a hit cap preserves the partial output and lets you raise the cap and resume rather than restart from zero.
  </Accordion>

  <Accordion title="Pick pause vs stop deliberately">
    `budget_action="pause"` returns a recoverable result — the partial `output` is preserved and `metadata["status"]` is `"paused"`. `budget_action="stop"` marks it terminal (`status="stopped"`). Pick `pause` when a human might raise the cap and continue; pick `stop` when the run should be killed unconditionally.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card icon="robot" href="/docs/features/autonomy-loop">
    Autonomy Loop — deep dive into iterative autonomy mode
  </Card>

  <Card icon="wallet" href="/docs/features/autonomy-budget">
    Autonomy Budget — cap the money and tokens a run can burn
  </Card>

  <Card icon="bullseye-arrow" href="/docs/features/goal-loop">
    Gate the autonomous loop on an independent acceptance-criteria judge
  </Card>
</CardGroup>
