How to Integrate Anthropic for insurance with pgvector for startups
Combining Anthropic with pgvector gives you a practical pattern for insurance AI agents: use Anthropic to reason over policy language, claims notes, and customer messages, then use pgvector to retrieve the most relevant internal documents, endorsements, and prior cases. For startups, this is the difference between a chatbot that guesses and an agent that answers with grounded context.
The architecture is simple: store embeddings for policy docs, claims playbooks, and underwriting guidelines in Postgres with pgvector, then let Anthropic generate responses using the retrieved context. That gives you faster support workflows, better claim triage, and fewer hallucinations.
Prerequisites
- •Python 3.10+
- •A running PostgreSQL database
- •The
pgvectorextension enabled in Postgres - •Anthropic API key
- •Python packages:
- •
anthropic - •
psycopg[binary] - •
pgvector - •
python-dotenvif you want.envloading
- •
- •A text embedding model or embedding service
- •Basic insurance content to index:
- •policy summaries
- •claims handling SOPs
- •underwriting rules
- •FAQ documents
Integration Steps
- •Install dependencies and enable pgvector
pip install anthropic psycopg[binary] pgvector python-dotenv
Enable the extension in your database:
CREATE EXTENSION IF NOT EXISTS vector;
- •Create a table for insurance knowledge
Use a vector column sized to your embedding model. If you’re using OpenAI-style 1536-dim embeddings or a similar model, keep the dimension consistent.
import os
import psycopg
from pgvector.psycopg import register_vector
DB_URL = os.environ["DATABASE_URL"]
with psycopg.connect(DB_URL) as conn:
register_vector(conn)
with conn.cursor() as cur:
cur.execute("""
CREATE TABLE IF NOT EXISTS insurance_docs (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
embedding VECTOR(1536) NOT NULL
);
""")
cur.execute("""
CREATE INDEX IF NOT EXISTS insurance_docs_embedding_idx
ON insurance_docs USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
""")
conn.commit()
- •Generate embeddings and store them in pgvector
Anthropic does not provide an embeddings API in the same way some other vendors do, so use a dedicated embedding model for vectorization. The important part is that Anthropic handles reasoning and generation, while pgvector handles retrieval.
import os
import psycopg
from pgvector.psycopg import register_vector
def embed_text(text: str) -> list[float]:
# Replace this with your embedding provider call.
# Must return a list of floats matching VECTOR(1536).
raise NotImplementedError
docs = [
{
"title": "Claims First Notice of Loss",
"content": "Collect claimant details, loss date, incident description, and supporting evidence."
},
{
"title": "Water Damage Exclusion",
"content": "Policies exclude damage caused by long-term seepage unless endorsed otherwise."
},
]
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
register_vector(conn)
with conn.cursor() as cur:
for doc in docs:
embedding = embed_text(doc["content"])
cur.execute(
"""
INSERT INTO insurance_docs (title, content, embedding)
VALUES (%s, %s, %s)
""",
(doc["title"], doc["content"], embedding),
)
conn.commit()
- •Retrieve relevant insurance context from pgvector
At query time, embed the user question and fetch the nearest documents.
import os
import psycopg
from pgvector.psycopg import register_vector
def embed_text(text: str) -> list[float]:
raise NotImplementedError
query = "Does this policy cover water damage from a slow leak?"
query_embedding = embed_text(query)
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
register_vector(conn)
with conn.cursor() as cur:
cur.execute(
"""
SELECT title, content
FROM insurance_docs
ORDER BY embedding <=> %s
LIMIT 3;
""",
(query_embedding,),
)
rows = cur.fetchall()
context = "\n\n".join([f"{title}: {content}" for title, content in rows])
print(context)
- •Send retrieved context to Anthropic for grounded answers
Use the Anthropic Messages API to generate an answer based on retrieved policy text.
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
question = "Does this policy cover water damage from a slow leak?"
message = client.messages.create(
model="claude-3-5-sonnet-latest",
max_tokens=300,
temperature=0,
messages=[
{
"role": "user",
"content": f"""
You are an insurance assistant.
Answer only using the provided context.
Context:
{context}
Question:
{question}
"""
}
],
)
print(message.content[0].text)
Testing the Integration
Run a full retrieval + generation test with one known policy rule and one query that should match it.
query = "Is gradual seepage covered under this policy?"
query_embedding = embed_text(query)
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
register_vector(conn)
with conn.cursor() as cur:
cur.execute(
"""
SELECT title, content
FROM insurance_docs
ORDER BY embedding <=> %s
LIMIT 1;
""",
(query_embedding,),
)
title, content = cur.fetchone()
response = client.messages.create(
model="claude-3-5-sonnet-latest",
max_tokens=200,
temperature=0,
messages=[
{
"role": "user",
"content": f"""
Context:
{title}: {content}
Question:
{query}
"""
}
],
)
print(response.content[0].text)
Expected output:
Based on the provided policy context, gradual seepage is excluded unless an endorsement explicitly adds coverage.
Real-World Use Cases
- •
Claims intake agent
- •Classify incoming claims notes against your internal playbooks.
- •Retrieve similar past cases from pgvector.
- •Have Anthropic draft next-step questions for adjusters.
- •
Policy Q&A assistant
- •Let customers ask coverage questions in plain English.
- •Pull exact clauses from indexed policy docs.
- •Generate answers that stay grounded in retrieved text.
- •
Underwriting support agent
- •Search underwriting guidelines by risk type or industry.
- •Summarize exceptions and required documentation.
- •Help junior underwriters make consistent decisions faster.
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