Spaces:
Running

WorkPilot-AI / core /agent /checkpoint.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
1.39 kB
"""Postgres checkpointer for durable agent state."""
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
from psycopg.rows import dict_row
from psycopg_pool import AsyncConnectionPool
def libpq_url(sqlalchemy_url: str) -> str:
"""SQLAlchemy URL -> libpq URL (drop the ``+driver`` part)."""
scheme, _, rest = sqlalchemy_url.partition("://")
return f"{scheme.split('+')[0]}://{rest}"
@asynccontextmanager
async def open_checkpointer(url: str, max_size: int = 10) -> AsyncIterator[AsyncPostgresSaver]:
pool = AsyncConnectionPool(
conninfo=libpq_url(url),
max_size=max_size,
kwargs={"autocommit": True, "prepare_threshold": 0, "row_factory": dict_row},
open=False,
)
await pool.open()
try:
yield AsyncPostgresSaver(pool) # type: ignore[arg-type]
finally:
await pool.close()
def setup_checkpoint_tables(owner_url: str) -> None:
"""Create LangGraph's checkpoint tables. Run as the owner role (migrations/bootstrap)."""
import psycopg
from langgraph.checkpoint.postgres import PostgresSaver
with psycopg.connect(libpq_url(owner_url), autocommit=True, row_factory=dict_row) as conn:
PostgresSaver(conn).setup()