> ## 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.

# Five-Layer Agent Stack

> The five layers every agent has — and which PraisonAI parameter lives at each

Every agent has five layers. When one misbehaves, the layer tells you where to look.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    subgraph MANAGED["⬡ Managed Agents — Where does it run?"]
        subgraph GRAPH["5 · Graph — Who runs when?"]
            subgraph LOOP["4 · Loop — When do we stop?"]
                subgraph HARNESS["3 · Harness — Can it act and be checked?"]
                    subgraph CONTEXT["2 · Context — Is the right thing in the window?"]
                        subgraph PROMPT["1 · Prompt — Did I say it clearly?"]
                            P[Agent]
                        end
                    end
                end
            end
        end
    end

    classDef prompt fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef context fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef harness fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef loop fill:#10B981,stroke:#7C90A0,color:#fff
    classDef graph fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef managed fill:#6366F1,stroke:#7C90A0,color:#fff

    class PROMPT prompt
    class CONTEXT context
    class HARNESS harness
    class LOOP loop
    class GRAPH graph
    class MANAGED managed
```

| Layer           | The question it answers             | PraisonAI                                                                                                                                                                |
| :-------------- | :---------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **1 · Prompt**  | Did I say it clearly?               | `instructions=`, `role`/`goal`/`backstory`, `output=`, `templates=`                                                                                                      |
| **2 · Context** | Is the right thing in the window?   | `memory=`, `knowledge=`, `context=`, handoff `ContextPolicy`                                                                                                             |
| **3 · Harness** | Can it act, and be checked?         | `tools=`, `MCP()`, `guardrails=`, `approval=`, `hooks=`, `sandbox=`                                                                                                      |
| **4 · Loop**    | When do we stop?                    | `execution=ExecutionConfig(...)`, `reflection=`, `autonomy=`, doom-loop detection                                                                                        |
| **5 · Graph**   | Who runs when, and who checks whom? | `AgentFlow`, `route()`, `parallel()`, `loop()`, `repeat()`                                                                                                               |
| **⬡ Managed**   | *Where does it actually run?*       | `backend=ManagedAgent(compute="e2b")` for one agent, or `AgentFlow(compute="docker")` / `AgentTeam(compute="docker")` to share one sandbox across every agent in the run |

***

## Quick tour of all five layers

<Steps>
  <Step title="Layer 1 · Prompt">
    Say it clearly — role, instructions, output format.
  </Step>

  <Step title="Layer 2 · Context">
    Put the right thing in the window — memory, knowledge, compression.
  </Step>

  <Step title="Layer 3 · Harness">
    Let it act and check it — tools, guardrails, approval.
  </Step>

  <Step title="Layer 4 · Loop">
    Decide when to stop — iteration caps, budgets, completion checks.
  </Step>

  <Step title="Layer 5 · Graph">
    Wire agents together — routing, parallelisation, orchestration.
  </Step>
</Steps>

***

## The five layers in depth

<AccordionGroup>
  <Accordion title="Layer 1 · Prompt — Did I say it clearly?">
    Role, instructions, examples, output format.

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

    agent = Agent(
        role="Senior Data Analyst",
        goal="Turn raw numbers into decisions",
        output="verbose",              # markdown-formatted output
    )
    agent.start("Summarise Q3 revenue trends")
    ```

    Learn more: [Agents](/docs/docs/concepts/agents), [Output](/docs/docs/concepts/output), [Templates](/docs/docs/concepts/templates).
  </Accordion>

  <Accordion title="Layer 2 · Context — Is the right thing in the window?">
    Write, select, compress, isolate — the four context operations, one parameter each.

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

    agent = Agent(
        instructions="You are a support engineer.",
        memory={"user_id": "u-42"},    # write    — persists across runs (needs a user_id)
        knowledge=["docs/"],           # select   — retrieves only what's relevant
        context="summarize",           # compress — auto-compacts before the limit
    )
    ```

    <Note>
      **Isolate** is `handoffs=[specialist]` — a sub-agent inherits the last few messages and the intersection of your tools, not your whole transcript.
    </Note>

    Learn more: [Context](/docs/docs/concepts/context), [Memory](/docs/docs/concepts/memory), [Knowledge](/docs/docs/concepts/knowledge), [Handoffs](/docs/docs/concepts/handoffs).
  </Accordion>

  <Accordion title="Layer 3 · Harness — Can it act, and be checked?">
    *Agent = Model + Harness.* Tool dispatch, plus the guides that steer before acting and the sensors that observe after.

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

    @tool
    def deploy(env: str) -> str:
        """Deploy the current build to an environment."""
        return f"Deployed to {env}"

    agent = Agent(
        name="ReleaseEngineer",
        instructions="You are a release engineer.",
        tools=[deploy, MCP("npx -y @modelcontextprotocol/server-filesystem /tmp")],
        approval=True,                 # guide — human gate before risky tools run
    )
    agent.start("Deploy to staging, then list the files you can read")
    ```

    Learn more: [Tools](/docs/docs/concepts/tools), [MCP](/docs/docs/concepts/mcp), [Guardrails](/docs/docs/concepts/guardrails), [Approval](/docs/docs/concepts/approval), [Hooks](/docs/docs/concepts/hooks).
  </Accordion>

  <Accordion title="Layer 4 · Loop — When do we stop?">
    Hard iteration caps, budget ceilings, no-progress detection and completion checks — every brake is explicit.

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

    agent = Agent(
        instructions="Fix the failing tests.",
        execution=ExecutionConfig(max_iter=30, max_budget=0.50, on_budget_exceeded="stop"),
        reflection=True,               # completion check — the agent grades its own answer
        autonomy=True,                 # required to drive the loop with run_autonomous()
    )
    result = agent.run_autonomous("Refactor the auth module", max_iterations=5)

    print(result.completion_reason)
    # goal | no_tool_calls | max_iterations | timeout | doom_loop | needs_help | error
    # (with on_budget_exceeded="stop", hitting the cap raises BudgetExceededError,
    #  surfaced here as completion_reason="error")
    ```

    <Warning>
      **Doom-loop detection is on by default.** Repeated identical tool calls and A→B→A→B oscillation get caught — while a poller whose output keeps changing does not.
    </Warning>

    Learn more: [Execution](/docs/docs/concepts/execution), [Reflection](/docs/docs/concepts/reflection), [Autonomy](/docs/docs/concepts/autonomy), [Budget](/docs/docs/concepts/budget), [Doom-Loop Detection](/docs/docs/features/doom-loop-detection).
  </Accordion>

  <Accordion title="Layer 5 · Graph — Who runs when, and who checks whom?">
    Topology as a versionable artifact: prompt chaining, routing, parallelisation, orchestrator-worker.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import AgentFlow, route, parallel, repeat

    flow = AgentFlow(steps=[
        classifier,
        route({"bug": [bug_agent], "feature": [feature_agent], "default": [triage]}),
        parallel([reviewer, tester]),                      # fan out, join automatically
        repeat(editor, until=lambda ctx: "approved" in ctx.previous_result.lower(),
               max_iterations=3),                          # evaluator–optimizer
    ])
    flow.run("Ticket #123: login fails on Safari")
    ```

    <Tip>
      The same graph is expressible in YAML with no Python at all.
    </Tip>

    Learn more: [AgentFlow](/docs/docs/concepts/agentflow), [Conditions](/docs/docs/concepts/conditions), [Process](/docs/docs/concepts/process).
  </Accordion>

  <Accordion title="⬡ Outside the stack: Managed Agents — Where does it actually run?">
    The harness is commoditising; **where** the agent executes is the next multiplier. Rather than burning your laptop's CPU, hand an agent a short-lived cloud sandbox — repo, tools and tests run there.

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

    # A. Tools run in a remote sandbox; the agent loop stays local
    sandboxed = ManagedAgent(
        provider="local", compute="e2b",   # or modal | daytona | flyio | docker | tenki
        config=LocalManagedConfig(model="gpt-4o-mini", name="RemoteTools"),
    )
    agent = Agent(name="builder", backend=sandboxed)

    # B. The entire agent loop runs in the cloud (needs ANTHROPIC_API_KEY;
    #    with no key set, ManagedAgent() falls back to a local loop)
    agent = Agent(name="teacher", backend=ManagedAgent())
    agent.start("Write a Python script that prints the first 10 primes, then run it")
    ```

    <Note>
      Sandboxes shut themselves down when idle (`auto_shutdown`, `idle_timeout_s`), and a post-setup snapshot is reused so the next run skips the image pull and dependency install. Commit a `.praisonai/environment.yaml` and the environment travels with the repo.
    </Note>

    <Note>
      Manage running sandboxes from the CLI — both commands take required positional arguments:

      ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
      praisonai managed sessions list <agent-id>
      praisonai managed sessions resume <session-id> "<prompt>"
      ```
    </Note>

    Learn more: [Managed Agents](/docs/docs/concepts/managed-agents), [E2B](/docs/docs/concepts/managed-agents-e2b), [Modal](/docs/docs/concepts/managed-agents-modal), [Daytona](/docs/docs/concepts/managed-agents-daytona), [Docker](/docs/docs/concepts/managed-agents-docker), [Local](/docs/docs/concepts/managed-agents-local).
  </Accordion>
</AccordionGroup>

***

## Which layer is my bug in?

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
flowchart TD
    Bug[Agent misbehaved] --> Q1{Wrong tone / format<br/>/ ignored role?}
    Q1 -->|Yes| L1[Layer 1: Prompt]
    Q1 -->|No| Q2{Missing facts,<br/>forgot prior turn?}
    Q2 -->|Yes| L2[Layer 2: Context]
    Q2 -->|No| Q3{Called wrong tool,<br/>bypassed check?}
    Q3 -->|Yes| L3[Layer 3: Harness]
    Q3 -->|No| Q4{Ran forever,<br/>stopped too early,<br/>burned budget?}
    Q4 -->|Yes| L4[Layer 4: Loop]
    Q4 -->|No| Q5{Wrong agent ran,<br/>steps out of order?}
    Q5 -->|Yes| L5[Layer 5: Graph]
    Q5 -->|No| L6[⬡ Managed: where it ran]

    classDef question fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef prompt fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef context fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef harness fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef loop fill:#10B981,stroke:#7C90A0,color:#fff
    classDef graph fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef managed fill:#6366F1,stroke:#7C90A0,color:#fff

    class Bug,Q1,Q2,Q3,Q4,Q5 question
    class L1 prompt
    class L2 context
    class L3 harness
    class L4 loop
    class L5 graph
    class L6 managed
```

***

## Related

<CardGroup cols={2}>
  <Card title="Layer 1 · Prompt" icon="user" href="/docs/docs/concepts/agents">
    Role, instructions, and output format.
  </Card>

  <Card title="Layer 2 · Context" icon="layer-group" href="/docs/docs/concepts/context">
    Memory, knowledge, and compression.
  </Card>

  <Card title="Layer 3 · Harness" icon="wrench" href="/docs/docs/concepts/tools">
    Tools, guardrails, and approval.
  </Card>

  <Card title="Layer 4 · Loop" icon="play" href="/docs/docs/concepts/execution">
    Iteration caps, budgets, and completion checks.
  </Card>

  <Card title="Layer 5 · Graph" icon="arrow-right" href="/docs/docs/concepts/agentflow">
    Routing, parallelisation, and orchestration.
  </Card>

  <Card title="⬡ Managed Agents" icon="cloud" href="/docs/docs/concepts/managed-agents">
    Where the agent actually runs.
  </Card>
</CardGroup>

<sub>Stack framing adapted from [The Five-Layer Agent Stack](https://mer.vin/2026/07/five-layer-agent-stack-match-bug-to-right-layer/) and [Agent Harnesses vs Orbs](https://mer.vin/2026/08/agent-harnesses-vs-orbs-why-remote-sandboxes-beat-local-agent-loops/).</sub>
