|
1 | | -import sqlite3 |
| 1 | +import atexit |
| 2 | +import os |
| 3 | +from functools import lru_cache |
2 | 4 | from typing import List, Optional |
3 | 5 |
|
4 | 6 | from dotenv import load_dotenv |
5 | 7 | from langchain_google_genai import ChatGoogleGenerativeAI |
6 | | -from langgraph.checkpoint.sqlite import SqliteSaver |
| 8 | +from langgraph.checkpoint.postgres import PostgresSaver |
7 | 9 | from langgraph.prebuilt import create_react_agent |
8 | 10 |
|
9 | 11 | load_dotenv() |
10 | 12 |
|
11 | 13 | # Global agent instance |
12 | 14 | _agent_executor = None |
13 | | -_memory = None |
| 15 | + |
| 16 | + |
| 17 | +@lru_cache |
| 18 | +def get_checkpointer(): |
| 19 | + DATABASE_URL = os.environ.get("DATABASE_URL") |
| 20 | + if not DATABASE_URL: |
| 21 | + raise RuntimeError("DATABASE_URL is not set. Point it to your Neon connection string.") |
| 22 | + |
| 23 | + cm = PostgresSaver.from_conn_string(DATABASE_URL) |
| 24 | + saver = cm.__enter__() # enter the context manager once |
| 25 | + atexit.register(lambda: cm.__exit__(None, None, None)) # clean shutdown |
| 26 | + saver.setup() # create tables on first run; no-op afterward |
| 27 | + return saver |
14 | 28 |
|
15 | 29 |
|
16 | 30 | def get_agent(): |
17 | 31 | """Get or create the agent instance.""" |
18 | | - global _agent_executor, _memory |
| 32 | + global _agent_executor |
19 | 33 |
|
20 | 34 | if _agent_executor is None: |
| 35 | + # Build LLM |
21 | 36 | llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash") |
22 | 37 |
|
23 | | - # Build persistent checkpointer |
24 | | - con = sqlite3.connect("db.sqlite3", check_same_thread=False) |
25 | | - _memory = SqliteSaver(con) |
26 | | - |
27 | 38 | # Create agent |
28 | 39 | _agent_executor = create_react_agent( |
29 | 40 | llm, |
30 | | - [], |
| 41 | + tools=[], |
31 | 42 | prompt="You are a helpful AI image editing assistant. \ |
32 | | - You help users with image editing tasks and provide guidance \ |
| 43 | + You help users with image editing tasks and provide guidance \ |
33 | 44 | on how to modify their images.", |
34 | | - checkpointer=_memory, |
| 45 | + checkpointer=get_checkpointer(), |
35 | 46 | ) |
36 | 47 |
|
37 | 48 | return _agent_executor |
|
0 commit comments