How to Integrate LangChain for insurance with PostgreSQL for AI agents
Combining LangChain for insurance with PostgreSQL gives you a practical pattern for building AI agents that can answer policy questions, retrieve claims history, and persist structured conversation state. In insurance workflows, that matters because the agent needs both reasoning and durable data access: LangChain handles orchestration, while PostgreSQL stores policy records, claim metadata, audit trails, and agent memory.
Prerequisites
- •Python 3.10+
- •A running PostgreSQL instance
- •A database user with read/write access
- •
pipinstalled - •Access to your LangChain for insurance package and credentials if your deployment requires them
- •Environment variables configured:
- •
DATABASE_URL=postgresql+psycopg://user:password@localhost:5432/insurance_ai - •Any LangChain provider keys required by your model backend
- •
Install the core packages:
pip install langchain langchain-community langchain-openai sqlalchemy psycopg[binary]
Integration Steps
- •
Create a PostgreSQL connection string and verify connectivity
Start by making sure your agent can reach the database. For production systems, keep credentials in environment variables and use SQLAlchemy as the connection layer.
import os
from sqlalchemy import create_engine, text
DATABASE_URL = os.getenv("DATABASE_URL")
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
with engine.connect() as conn:
result = conn.execute(text("SELECT version();"))
print(result.fetchone())
If this fails, fix networking, credentials, or SSL settings before moving on.
- •
Create the insurance tables your agent will query
Your agent needs structured records to reason over. For insurance use cases, keep policy details and claims separate so retrieval stays predictable.
from sqlalchemy import MetaData, Table, Column, Integer, String, DateTime, Text
from sqlalchemy.sql import func
metadata = MetaData()
policies = Table(
"policies",
metadata,
Column("id", Integer, primary_key=True),
Column("policy_number", String(50), unique=True, nullable=False),
Column("customer_name", String(255), nullable=False),
Column("product_type", String(100), nullable=False),
Column("status", String(50), nullable=False),
Column("updated_at", DateTime(timezone=True), server_default=func.now(), onupdate=func.now()),
)
claims = Table(
"claims",
metadata,
Column("id", Integer, primary_key=True),
Column("claim_number", String(50), unique=True, nullable=False),
Column("policy_number", String(50), nullable=False),
Column("claim_status", String(50), nullable=False),
Column("notes", Text),
)
metadata.create_all(engine)
- •
Connect LangChain to PostgreSQL-backed tools
In LangChain for insurance workflows, the cleanest pattern is to expose database queries as tools. The agent then calls those tools when it needs policy or claim data.
import os
from langchain_openai import ChatOpenAI
from langchain_community.utilities import SQLDatabase
from langchain_community.agent_toolkits import create_sql_agent
db = SQLDatabase.from_uri(os.getenv("DATABASE_URL"))
llm = ChatOpenAI(
model="gpt-4o-mini",
temperature=0,
)
agent = create_sql_agent(
llm=llm,
db=db,
verbose=True,
)
This gives you an agent that can translate natural language into SQL against PostgreSQL. For insurance teams, that means questions like “Show open claims for policy P-1002” become executable queries instead of hardcoded flows.
- •
Add a structured insert flow for policy or claim updates
Agents should not only read from PostgreSQL; they should also write back validated updates. Use parameterized SQL through SQLAlchemy to avoid injection issues.
from sqlalchemy import text
def add_claim(claim_number: str, policy_number: str, claim_status: str, notes: str):
stmt = text("""
INSERT INTO claims (claim_number, policy_number, claim_status, notes)
VALUES (:claim_number, :policy_number, :claim_status, :notes)
ON CONFLICT (claim_number)
DO UPDATE SET
policy_number = EXCLUDED.policy_number,
claim_status = EXCLUDED.claim_status,
notes = EXCLUDED.notes
RETURNING id;
""")
with engine.begin() as conn:
row = conn.execute(stmt, {
"claim_number": claim_number,
"policy_number": policy_number,
"claim_status": claim_status,
"notes": notes,
}).fetchone()
return row[0]
You can call this from an agent tool after extracting structured fields from user input.
- •
Wrap the database operation as a LangChain tool
This is the production pattern you want: the model reasons; the tool executes bounded database work.
from langchain_core.tools import tool
@tool
def create_claim_record(claim_number: str, policy_number: str, claim_status: str, notes: str) -> str:
"""Create or update a claim record in PostgreSQL."""
claim_id = add_claim(claim_number, policy_number, claim_status, notes)
return f"Claim saved with id={claim_id}"
# Example direct invocation
print(create_claim_record.invoke({
"claim_number": "CLM-9001",
"policy_number": "POL-1002",
"claim_status": "open",
"notes": "Customer reported roof damage after storm."
}))
Testing the Integration
Run a simple end-to-end check: insert a record and ask the agent to retrieve it.
with engine.begin() as conn:
conn.execute(text("""
INSERT INTO policies (policy_number, customer_name, product_type, status)
VALUES ('POL-1002', 'Amina Patel', 'Home Insurance', 'active')
ON CONFLICT (policy_number) DO NOTHING;
"""))
response = agent.invoke({
"input": "Find the active home insurance policy for Amina Patel."
})
print(response["output"])
Expected output:
The active home insurance policy for Amina Patel is POL-1002.
If you added claims data too:
print(create_claim_record.invoke({
"claim_number": "CLM-9001",
"policy_number": "POL-1002",
"claim_status": "open",
"notes": "Storm damage reported by customer."
}))
Expected output:
Claim saved with id=1
Real-World Use Cases
- •
Policy servicing agents
- •Answer coverage questions from PostgreSQL-backed policy tables.
- •Update customer records after validating user intent through LangChain.
- •
Claims triage assistants
- •Pull recent claims history and classify incoming incidents.
- •Write normalized claim summaries back into PostgreSQL for downstream workflows.
- •
Internal underwriting copilots
- •Retrieve prior submissions and risk notes from relational storage.
- •Generate draft recommendations while keeping audit-friendly records in Postgres.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit