How to Integrate Next.js for insurance with Vercel AI SDK for production AI
When you combine Next.js for insurance with Vercel AI SDK, you get a clean path from product UI to production-grade AI workflows. The useful part is not “chatbot in a box” — it’s building insurance-facing agents that can quote, triage claims, explain policy terms, and hand off to humans with the right context.
The integration pattern is simple: let Next.js for insurance handle the customer workflow and domain logic, then use Vercel AI SDK as the orchestration layer for model calls, tool routing, and streaming responses.
Prerequisites
- •Python 3.11+
- •A running Next.js for insurance app with API access enabled
- •A Vercel project with Vercel AI SDK installed
- •API keys configured in environment variables:
- •
NEXTJS_INSURANCE_API_KEY - •
VERCEL_AI_API_KEY
- •
- •
httpxinstalled for outbound API calls - •Basic knowledge of:
- •REST APIs
- •JSON payloads
- •server-side route handlers
Integration Steps
- •
Create a Python client for Next.js for insurance
Your first job is to wrap the insurance app’s API so your agent can fetch policies, claims, and customer records. Keep this client thin; don’t bury business logic here.
import os import httpx class NextJsInsuranceClient: def __init__(self): self.base_url = os.environ["NEXTJS_INSURANCE_BASE_URL"] self.api_key = os.environ["NEXTJS_INSURANCE_API_KEY"] self.client = httpx.Client( base_url=self.base_url, headers={ "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", }, timeout=30.0, ) def get_policy(self, policy_id: str) -> dict: response = self.client.get(f"/api/policies/{policy_id}") response.raise_for_status() return response.json() def create_claim(self, policy_id: str, claim_type: str, description: str) -> dict: payload = { "policyId": policy_id, "claimType": claim_type, "description": description, } response = self.client.post("/api/claims", json=payload) response.raise_for_status() return response.json() - •
Wrap Vercel AI SDK calls behind a Python service boundary
Vercel AI SDK is typically used from the app layer, but in production systems you want a stable service boundary. In practice, that means your Python backend should call your Next.js route that uses
streamText()orgenerateText()from the Vercel AI SDK.import os import httpx class VerceIaiGateway: def __init__(self): self.base_url = os.environ["VERCEL_AI_GATEWAY_URL"] self.client = httpx.Client(timeout=60.0) def generate_claim_summary(self, policy: dict, claim: dict) -> dict: payload = { "model": "gpt-4o-mini", "messages": [ { "role": "system", "content": "You are an insurance operations assistant. Summarize claims clearly and conservatively." }, { "role": "user", "content": f"Policy: {policy}\nClaim: {claim}" } ] } response = self.client.post(f"{self.base_url}/api/ai/generate", json=payload) response.raise_for_status() return response.json() - •
Connect the two services in an orchestration layer
This is where the actual agent behavior lives. Fetch policy context from Next.js for insurance, send it to the Vercel AI SDK-backed endpoint, then persist the result back into your insurance system.
class InsuranceAgentOrchestrator: def __init__(self): self.insurance = NextJsInsuranceClient() self.ai = VerceIaiGateway() def summarize_and_attach_claim(self, policy_id: str, claim_id: str) -> dict: policy = self.insurance.get_policy(policy_id) # In a real system you'd fetch claim details too. claim = {"claimId": claim_id, "status": "open", "notes": ["Customer reports water damage"]} summary_result = self.ai.generate_claim_summary(policy=policy, claim=claim) # Example persistence call back into your insurance app. # Replace with your real endpoint if different. attach_payload = { "claimId": claim_id, "aiSummary": summary_result["text"], "source": "vercel-ai-sdk" } attach_response = httpx.post( f"{os.environ['NEXTJS_INSURANCE_BASE_URL']}/api/claims/{claim_id}/notes", headers={"Authorization": f"Bearer {os.environ['NEXTJS_INSURANCE_API_KEY']}"}, json=attach_payload, timeout=30.0, ) attach_response.raise_for_status() return { "policy": policy, "claimSummary": summary_result["text"], "attached": True } - •
Use Vercel AI SDK route handlers for streaming responses
For agent UX, streaming matters. In your Next.js route handler, use
streamText()so adjusters or underwriters see partial output immediately instead of waiting on a full completion.from textwrap import dedent nextjs_route_handler_example = dedent(""" import { streamText } from 'ai'; import { openai } from '@ai-sdk/openai'; export async function POST(req: Request) { const { messages } = await req.json(); const result = streamText({ model: openai('gpt-4o-mini'), messages, system: 'You are an insurance assistant handling claims intake and policy questions.' }); return result.toDataStreamResponse(); } """) print(nextjs_route_handler_example) - •
Add guardrails before writing anything back
Don’t let the model write directly into claims or policy records without validation. Run structured checks in Python before calling your insurance API.
from pydantic import BaseModel, Field class ClaimNote(BaseModel): claim_id: str ai_summary: str = Field(min_length=20) confidence: float = Field(ge=0.0, le=1.0) def persist_safe_note(note_data: dict): note = ClaimNote(**note_data) if note.confidence < 0.7: raise ValueError("AI confidence too low for auto-persist") return httpx.post( f"{os.environ['NEXTJS_INSURANCE_BASE_URL']}/api/claims/{note.claim_id}/notes", headers={"Authorization": f"Bearer {os.environ['NEXTJS_INSURANCE_API_KEY']}"}, json=note.model_dump(), )
Testing the Integration
Run an end-to-end smoke test that fetches a policy, generates a summary through the Vercel AI SDK-backed endpoint, and writes a note back to the insurance app.
def test_integration():
orchestrator = InsuranceAgentOrchestrator()
result = orchestrator.summarize_and_attach_claim(
policy_id="POL-100245",
claim_id="CLM-88912"
)
print(result)
if __name__ == "__main__":
test_integration()
Expected output:
{
'policy': {'id': 'POL-100245', 'type': 'home', 'status': 'active'},
'claimSummary': 'Customer reported water damage affecting the kitchen ceiling...',
'attached': True
}
Real-World Use Cases
- •
Claims intake assistant
- •Pull policy data from Next.js for insurance
- •Use Vercel AI SDK to classify loss type and draft intake notes
- •Save structured summaries back into the claims record
- •
Underwriting support agent
- •Fetch applicant and coverage data from your insurance backend
- •Generate risk summaries with
generateText() - •Flag missing documents or inconsistent answers before submission
- •
Policy servicing copilot
- •Answer coverage questions using live policy context
- •Stream responses with
streamText() - •Escalate edge cases to human agents with full conversation history
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