> ## Documentation Index
> Fetch the complete documentation index at: https://agno-v2.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Cancel Run Persistence

> Cancel a team run mid-stream and verify that partial content and messages are preserved in the database.

```python cancel_run_persistence.py theme={null}
"""
Cancel Run Persistence
======================
Cancel a team run mid-stream and verify that partial content
and messages are preserved in the database.

Requires: PostgreSQL running on localhost:5532 (see cookbook/scripts/run_pgvector.sh)
"""

from agno.agent import Agent
from agno.db.postgres import PostgresDb
from agno.models.openai import OpenAIResponses
from agno.run.team import TeamRunEvent
from agno.team import Team

# ---------------------------------------------------------------------------
# Create Members
# ---------------------------------------------------------------------------
researcher = Agent(
    name="Researcher",
    model=OpenAIResponses(id="gpt-5.4"),
    instructions="You are a researcher. Write detailed responses.",
)

# ---------------------------------------------------------------------------
# Create Team
# ---------------------------------------------------------------------------
team = Team(
    name="ResearchTeam",
    members=[researcher],
    model=OpenAIResponses(id="gpt-5.4"),
    db=PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai"),
    store_tool_messages=True,
    store_history_messages=True,
)


# ---------------------------------------------------------------------------
# Run Team
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    run_id = None
    cancelled = False
    content_chunks: list = []

    for event in team.run(
        input=(
            "Write a very long essay about the history of artificial intelligence"
            " with at least 10 major milestones."
        ),
        stream=True,
        stream_events=True,
    ):
        if run_id is None and hasattr(event, "run_id") and event.run_id:
            run_id = event.run_id

        if hasattr(event, "content") and event.content:
            content_chunks.append(event.content)
            print(event.content, end="", flush=True)

        # Cancel after collecting some content
        if len(content_chunks) >= 20 and run_id and not cancelled:
            team.cancel_run(run_id)
            cancelled = True

        if hasattr(event, "event") and event.event == TeamRunEvent.run_cancelled:
            print("\nRun was cancelled")
            break

    # Verify persistence
    print("\n--- Verification ---")
    session = team.get_session(session_id=team.session_id)
    if session and session.runs:
        last_run = session.runs[-1]
        print(f"Status: {last_run.status}")
        print(f"Content length: {len(last_run.content or '')}")
        print(f"Messages: {len(last_run.messages or [])}")
```

## Run the Example

<Snippet file="create-venv-step.mdx" />

**1. Install dependencies**

```bash theme={null}
uv pip install -U agno "psycopg[binary]" openai sqlalchemy
```

**2. Export your OpenAI API key**

```bash Mac/Linux theme={null}
export OPENAI_API_KEY="your_openai_api_key_here"
```

```bash Windows theme={null}
$Env:OPENAI_API_KEY="your_openai_api_key_here"
```

<Snippet file="run-pgvector-step.mdx" />

**3. Run the example**

Save the code above as `cancel_run_persistence.py`, then run:

```bash theme={null}
python cancel_run_persistence.py
```

Full source: [cookbook/03\_teams/14\_run\_control/cancel\_run\_persistence.py](https://github.com/agno-agi/agno/blob/v3.0.4/cookbook/03_teams/14_run_control/cancel_run_persistence.py)


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