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

# Resource Lifecycle

> Automatically clean up agents, shared memory, and connections using with or async with

Use `with` or `async with` on `PraisonAIAgents` to close agents, memory stores, and connections when a workflow finishes.

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

researcher = Agent(name="Researcher", instructions="Research topics thoroughly")
task = Task(description="Research quantum computing", agent=researcher)

with PraisonAIAgents(agents=[researcher], tasks=[task]) as workflow:
    result = workflow.start()

print(result)
```

The user runs agents inside a context manager; leaving the block closes agents, memory stores, and connections automatically.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Resource Lifecycle"
        A[Create Team] --> B[Run Tasks]
        B --> C{Exit Block}
        C --> D[close agents]
        C --> E[close memory]
        D --> F[Clean Exit]
        E --> F
    end

    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef tool fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff

    class A agent
    class B,C tool
    class D,E,F output
```

## Quick Start

<Steps>
  <Step title="Simple Usage">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, Task, PraisonAIAgents

    researcher = Agent(name="Researcher", instructions="Research topics thoroughly")
    task = Task(description="Research quantum computing", agent=researcher)

    with PraisonAIAgents(agents=[researcher], tasks=[task]) as workflow:
        result = workflow.start()

    print(result)
    ```
  </Step>

  <Step title="With Configuration">
    Async usage with shared memory inside a FastAPI endpoint:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    import asyncio
    from fastapi import FastAPI
    from praisonaiagents import Agent, Task, PraisonAIAgents, ChromaMemory

    app = FastAPI()

    @app.post("/research")
    async def research_topic(topic: str):
        researcher = Agent(name="Researcher", instructions="Research topics")
        task = Task(description=f"Research {topic}", agent=researcher)

        async with PraisonAIAgents(
            agents=[researcher],
            tasks=[task],
            shared_memory=ChromaMemory(),
        ) as workflow:
            result = await workflow.astart()

        return {"research": result}
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Team as AgentTeam
    participant Agents
    participant Memory as SharedMemory

    User->>Team: with AgentTeam(...) as team
    Team-->>User: self
    User->>Team: team.start()
    Team->>Agents: execute tasks
    Agents-->>Team: results
    User->>Team: exit with block
    Team->>Agents: close() each
    Team->>Memory: close()
    Team-->>User: cleanup complete
```

| Entry point | Method | Description |
| - | - | - |
| `with team:` | `__enter__` / `__exit__` | Sync — calls `close()` on exit |
| `async with team:` | `__aenter__` / `__aexit__` | Async — prefers `aclose()` when available |
| Manual | `team.close()` | Explicit cleanup for long-running workers |

***

## Common Patterns

### Shared memory cleanup

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

with PraisonAIAgents(
    agents=[researcher],
    tasks=[task],
    shared_memory=ChromaMemory(),
) as workflow:
    result = workflow.start()
# ChromaDB connection closed here
```

### Long-running worker shutdown

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
workflow = PraisonAIAgents(agents=[researcher])
try:
    workflow.add_task(Task(description="Research AI", agent=researcher))
    workflow.start()
finally:
    workflow.close()
```

### Per-request isolation in servers

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
@app.post("/analyse")
async def analyse(data: str):
    agent = Agent(name="Analyzer", instructions="Analyse data")
    async with PraisonAIAgents(agents=[agent]) as workflow:
        return await workflow.astart()
```

### HTTP invoke API — no manual cleanup needed

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# In an n8n / HTTP invoke deployment you do NOT need to wrap invokes
# in with / try/finally — the wrapper closes each per-request clone.
# Just register the template once and serve.

from praisonaiagents import Agent
from praisonai.api.agent_invoke import register_agent

register_agent("assistant", Agent(name="assistant", instructions="…"))
# praisonai serve agents.yaml — every POST /invoke closes its clone.
```

See [n8n API → Per-request cleanup](/docs/features/n8n-api).

***

## Best Practices

<AccordionGroup>
  <Accordion title="Prefer context managers over manual close()">
    `with` and `async with` guarantee cleanup even when exceptions occur.
  </Accordion>

  <Accordion title="Cleanup is best-effort">
    `close()` logs warnings on failure but does not raise — cleanup failures will not mask the original error.
  </Accordion>

  <Accordion title="Do not reuse a team after exiting its block">
    Create a new `PraisonAIAgents` instance for each batch or request.
  </Accordion>

  <Accordion title="Create one team per request in servers">
    Avoid sharing a global workflow across HTTP requests — isolate resources per call.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Advanced Memory System" icon="brain" href="/docs/features/advanced-memory">
    Shared memory stores that benefit from automatic cleanup
  </Card>

  <Card title="MongoDB Memory" icon="database" href="/docs/features/mongodb-memory">
    MongoDB-backed memory with connection lifecycle support
  </Card>

  <Card title="Agent Lifecycle Cleanup" icon="broom" href="/docs/features/agent-lifecycle-cleanup">
    Per-agent teardown of clients, MCP tools, and breakers
  </Card>

  <Card title="n8n API" icon="code" href="/docs/features/n8n-api">
    Per-request clone cleanup in the HTTP invoke endpoint
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.