保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Agentic AI

Connecting My LangGraph AI Agent to Postgres

How to run the backend locally with Docker or in the cloud Soner Yıldırım August 28, 20265 min read Photo by Towfiqu barbhuiya on Unsplash Photo by Towfiqu barbhuiya on Unsplash In the first three articles of this series, I built a stateful LangGraph agent that handles a 15-minute booking process and wrapped it up with a Streamlit UI to improve user experience, and added a proper backend with Postgres database. The journey of this AI agent started when I had a chat with a customer service representative for a cleaning service. The agent handles the entire booking process like a real customer service representative. It’s a LangGraph-based agent that orchestrates the following operations:

In this article, we will test the Postgres backend using both Docker and a hosted Postgres. The full source code of this project is available on GitHub at customer-service-agent. Feel free to clone the repo and test it yourself. Learn this step by step with the interactive AI Agents roadmap.

Agent Structure

The following diagram shows the structure (i.e. graph workflow) of our AI agent: Conversation progress lives in LangGraph AgentState and is saved as checkpoints. When the agent offers time slots, it reads existing bookings from the database so it does not propose a time that is already taken. When the customer confirms a booking, the agent writes one booking row (technician, time range, address, price).

Testing the database

As I explained in the previous article, the agent has two persistence modes, which are in-memory and Postgres. In-memory is for quick testing and demo purposes. If DATABASE_URL is unset, the app uses InMemoryBookingRepository and MemorySaver. No tables are created. In order to run a local test with Streamlit UI, we first install dependencies with poetry install and then create a .env file by copying the .env.example . bash

poetry install
cp .env.example .env 

We need to set OPENAI_API_KEY in .env . We can leave DATABASE_URL empty for this test. Then, we can start the Stremlit UI at localhost:8501 using the following command: bash

poetry run streamlit run customer_service_agent/streamlit_app.py

Then we see the following Streamlit UI: Here is a small chat I had with the agent: If you haven't read the previous articles, the AI agent can understand If all required information is already present and proceed directly to calculating and presenting a quote. If I don't give the size or address in the first message, agent would ask for these before calculating the price. We can complete a booking in the UI but conversation state disappear when the app restarts. To actually have data stored, we need to use the database options.

Testing with Docker

Why testing with Docker

We also have the option to test the project with Docker. It allows for testing against Postgres without having to installing a real database in our computers. Testing with Docker mimics the same database we would have in production but locally. The app talks to an actual PostgreSQL server. Docker also makes it reproducible for everyone. The URL and credentials live in docker-compose.yml / .env.example. You get the same setup as I have used. Thanks to Docker, the app will be isolated from the rest of the computer. The database runs in a container. We can stop it (docker compose down) or wipe it (docker compose down -v) without touching other apps. So Docker lets us test the durable backend on a real Postgres instance in minutes, with the same connection string every time, and without installing Postgres on our laptop.

How to test with Docker

This project has a docker-compose.yml file that starts a container with PostgreSQL 16: yaml

services:
  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: booking
      POSTGRES_PASSWORD: booking
      POSTGRES_DB: booking_agent
    ports:
      - "5432:5432"
    volumes:
      - booking_pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U booking -d booking_agent"]
      interval: 5s
      timeout: 5s
      retries: 10

volumes:
  booking_pgdata:

Docker pulls the official Postgres image and runs a database server inside the container. Streamlit app still runs locally and connects to that container over localhost:5432. Database files are stored in a Docker volume (booking_pgdata) , which is a persistent disk storage managed by Docker. It's not in RAM so data stays in the container unless we delete the volume. In order to test it Docker, you need to Docker Desktop installed in your computer. Open Docker Desktop and wait until you see "Engine is running" or "Docker is running". Then, we can start the container using the following command: bash

docker compose up -d

And we need to add DATABASE_URL in our .env file: bash

DATABASE_URL=postgresql://booking:booking@localhost:5432/booking_agent

Then, we can run the app using the following command: bash

poetry run streamlit run customer_service_agent/streamlit_app.py

After running this command, Streamlit UI starts. I completed a test booking: To verify it works properly, I open a second browser (localhost:8501) and asked for the same service. This time, it did not offer the time slop I previously booked: We can also see it's running on Docker Desktop: Streamlit and Docker Postgres are separate processes. Restarting Streamlit only restarts the Python app. The Postgres container keeps running unless we stop it. Also, the data lives in the Docker volume, not in Streamlit memory. So when we schedule a new appointment, the app sees the previous bookings in the database. We only lose the database only if we stop or remove the container and delete the volume (docker compose down -v). bash

docker compose down -v
[+] down 3/3
 ✔ Container customer-service-agent-postgres-1  Removed                                                   0.2s
 ✔ Volume customer-service-agent_booking_pgdata Removed                                                   0.1s
 ✔ Network customer-service-agent_default       Removed 

Testing with a hosted Postgres

We don't need to use Docker if we have Postgres in the cloud (e.g. Supabase, RDS). We can simply create a Postgres database in the provider's dashboard and copy the connection string. It looks something like this: postgresql://USER:PASSWORD@HOST:PORT/DATABASE We then put that string in .env as DATABASE_URL. Then, we start the app as we did before: bash

poetry run streamlit run customer_service_agent/streamlit_app.py

The app behavior is identical to Docker. The only difference is where Postgres runs. It now runs on a remote host. We are gradually turning this customer service agent into a product that could provide real business value. There is still more to do. We can add other channels, such as WhatsApp. We also need a safety layer to reduce prompt injection risk. The booking workflow and chat experience can be improved as well. I will cover these in upcoming articles. Thank you for reading.

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


Written By

Soner Yıldırım

See all from Soner Yıldırım Agentic AiLanggraphPostgresProgrammingPython Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

Solving a Video sequencing puzzle

Software Engineering Doing Data Science from Scratch: Video clip processing David Moore December 8, 20206 min read

Vibe Coding with AI: Best Practices for Human-AI Collaboration in Software Development

Agentic AI Accelerate coding with AI while staying in control and building reliable, production-ready software. Partha Sarkar March 19, 202614 min read

Agentic AI and the Future of Python Project Management Tooling

Agentic AI Introducing a pyramid framework of evolution, accelerating and decelerating factors, and strategic recommendations for incumbents and new entrants Chinmay Kakatkar September 8, 20259 min read

Lessons Learned from Upgrading to LangChain 1.0 in Production

Agentic AI What worked, what broke, and why I did it Clara Chong December 15, 20255 min read

Warp Space and Time with Radial Heatmaps

Data Science A unique data visualization for time series and cyclical data using Python and HoloViews Cole Hagen April 10, 20223 min read

Coding an Intelligent Battleship Agent

Data Science Developing a strategy from random guessing to superhuman performance Aydin Schwartz April 14, 20228 min read

Unified Agentic Memory Across Harnesses Using Hooks

Agentic AI How hook implementation gives Claude Code, Codex, and Cursor persistent memory via Neo4j, without locking you into any one of them. Tomaz Bratanic May 8, 20268 min read

Fast Anomaly Detection With Python

Machine Learning HBOS vs iForest on MacBook Pro M1 Anthony Cavin July 1, 20226 min read

Depth-Aware Object Insertion in Videos using Python

Instructions for placing 3D models in videos with a depth-aware method using Python Berkan Zorlubas August 29, 20239 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close