Spaces:
Running
Running
File size: 1,391 Bytes
fd5dd94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | """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()
|