agent_run_cancel_persistence.py
"""
Cancel Run Persistence
======================
Cancel an agent 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.agent import RunEvent
# ---------------------------------------------------------------------------
# Create Agent
# ---------------------------------------------------------------------------
agent = Agent(
name="Storyteller",
model=OpenAIResponses(id="gpt-5.4"),
instructions="You are a storyteller. Write very long detailed stories.",
db=PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai"),
store_tool_messages=True,
store_history_messages=True,
)
# ---------------------------------------------------------------------------
# Run Agent
# ---------------------------------------------------------------------------
if __name__ == "__main__":
run_id = None
cancelled = False
content_chunks: list = []
for event in agent.run(
input="Write a very long story about a dragon who learns to code. Make it at least 2000 words.",
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:
agent.cancel_run(run_id)
cancelled = True
if hasattr(event, "event") and event.event == RunEvent.run_cancelled:
print("\nRun was cancelled")
break
# Verify persistence
print("\n--- Verification ---")
session = agent.get_session(session_id=agent.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
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activate
uv venv --python 3.12
.venv\Scripts\activate
Export your OpenAI API key
export OPENAI_API_KEY="your_openai_api_key_here"
$Env:OPENAI_API_KEY="your_openai_api_key_here"
Run PgVector
docker run -d \
-e POSTGRES_DB=ai \
-e POSTGRES_USER=ai \
-e POSTGRES_PASSWORD=ai \
-e PGDATA=/var/lib/postgresql/data/pgdata \
-v pgvolume:/var/lib/postgresql/data \
-p 5532:5432 \
--name pgvector \
agnohq/pgvector:18