Is it bad practice to create_agent all the time?

Hey guys,

I cant seem to wrap this around my head

When I use PostgresSQL for memory, it seems that I have to do create_agent all the time since PostgresSQL is required to be wrapped with the with statement

i.e:


with PostgresSaver.from_conn_string(SUPABASE_DB_URL) as checkpointer:
   agent = build_agent("gpt-4o-mini", checkpointer) thread_id = "user-123"
   config = {"configurable": {"thread_id": "user-123"}}

    print(invoke_agent(agent, thread_id, "What's the capital of the moon?"))  
    

So does that mean every time I ask a follow up question, I’ll need to call build_agent again? There has to be a better way to do this (other than refactoring to a function) because won’t it be redundant and create memory issues?

Thanks

1 Like

hi @MartinYTSo

try this:

# Create the context manager
_checkpointer_cm = PostgresSaver.from_conn_string(os.getenv("POSTGRES_URI"))
# Enter it once and keep the real PostgresSaver
checkpointer = _checkpointer_cm.__enter__()
checkpointer.setup()  # once on startup
# ...
agent = create_agent("gpt-4o-mini", checkpointer=checkpointer)
1 Like

Thank you it worked! may I ask what is your logic?

your welcome @MartinYTSo :slight_smile:
What do you mean by “my logic”?

Huge favour: could you mark this post as Solved if it solves your issue?

I mean how did you know what to do. I know this is kind of trivial but I’m kind of new to langchain

No need to call the build agent each time. Create the agent once inside the with block and reuse it for all your questions.

Hmmm I read articles, study the codebases, help here on the forum solving problems, code… I dunno, I just like programming and Langchain specifically :slight_smile:

1 Like