Autonomous Insurance Quotation Platform
Asynchronous multi-carrier simulation engine for auto insurance: headless browser orchestration, strict policy-emission guardrails, canonical PDF normalization, and sub-90s quote generation.
Context: Engineered for a licensed Portuguese insurance brokerage (ASF-regulated) to automate multi-carrier quotation workflows, eliminating manual portal entry while enforcing hard policy-emission containment boundaries.
Traditional insurance distribution in Southern Europe remains dependent on legacy web portals. Unlike modern banking or travel sectors with open API standards, underwriters (such as Allianz, Fidelidade, Tranquilidade, and Mapfre) provide independent brokers with authenticated web interfaces designed strictly for manual human data entry.
For personal auto insurance (Seguro Automóvel), evaluating options across the market required a broker to spend 30 to 45 minutes per client: re-entering identical driver, vehicle, and bonus-malus parameters across 10 to 14 separate carrier portals, waiting for sequential page reloads, downloading disparate PDF proposals, and manually transcribing premiums into comparative spreadsheets.
We engineered and deployed a containerized orchestration platform that compresses this multi-carrier simulation cycle down to under 90 seconds while enforcing zero-emission safety boundaries and providing a Human-in-the-Loop (HITL) audit surface.
System Architecture
The platform runs as an asynchronous worker cluster deployed on Scaleway (EU-sovereign cloud infrastructure in fr-par):
Sovereign Cloud Deployment on Scaleway
Brokerage operations process sensitive personally identifiable data (driver tax IDs, license issuance histories, vehicle registrations) governed by GDPR and ASF regulatory standards. We deployed the production system on Scaleway (fr-par region), providing three operational advantages:
- Strict Data Residency: Guaranteeing that customer data, vehicle certificates, and generated proposal documents never leave European jurisdiction or cross CLOUD Act boundaries.
- Private VPC Isolation: Ingestion APIs, worker containers, and data stores communicate across a private Scaleway VPC. Only the public ingress endpoint is exposed to the broker's web interface, while the task broker and storage buckets remain entirely unroutable from the public internet.
- Managed Queue & Object Store: Scaleway Managed Redis buffers simulation jobs and enforces per-carrier concurrency limits (preventing outbound rate-limiting or anti-bot blocks from insurance portals). Raw outputs, Playwright execution traces, and carrier proposal PDFs are persisted to Scaleway Object Storage (S3-compatible) with immutable audit logging.
- Predictable Unit Economics: Standard hyperscalers (AWS, Azure) levy steep bandwidth and egress penalties for headless browser workloads and PDF archiving. Scaleway provided flat-rate, high-performance compute and zero-egress internal networking, keeping total production infrastructure costs under €85/month.
Ingress & Automotive Entity Validation
Every quote request begins with vehicle and driver validation against Portuguese regulatory schemas:
- Automotive Registration: Formatting Portuguese license plates (
AA-00-AA,00-AA-00,00-00-AA,AA-00-00) and determining vehicle age, fuel classification, and curb weight. - Driver Profile: Validation of Portuguese fiscal identification numbers (NIF), driver license issuance date, birth date, and claims-free historical bonus-malus scale (escalão de bónus-malus).
- Coverage Requirements: Distinguishing mandatory third-party liability (Responsabilidade Civil) from comprehensive own-damage options (Danos Próprios), roadside assistance levels (Assistência em Viagem), and glass breakage riders (Quebra Isolada de Vidros).
Engineering Challenges
1. The Zero-Emission Safety Boundary
In commercial insurance brokerage portals, the UI pathway for calculating a quote and the pathway for legally binding a policy share the same multi-step workflow. Clicking past the quotation stage can immediately trigger policy emission (emissão de apólice), creating legally binding financial liability for the broker under Portuguese insurance law (ASF regulation).
To eliminate this operational hazard, we implemented defense-in-depth safety boundaries directly in code:
# workers/safety/guardrails.py
import re
from playwright.async_api import Page, Route
FORBIDDEN_PATTERNS = [
re.compile(r"/emitir", re.IGNORECASE),
re.compile(r"/confirmar-apolice", re.IGNORECASE),
re.compile(r"/finalizar-contratacao", re.IGNORECASE),
]
FORBIDDEN_TEXT_SELECTORS = [
"button:has-text('Emitir Apólice')",
"button:has-text('Confirmar Contratação')",
"button:has-text('Submeter Proposta Definitiva')",
]
async def attach_emission_safety_gate(page: Page) -> None:
"""
Installs network route interceptors and DOM mutation observers that abort
the automation run if execution attempts to progress beyond quote generation.
"""
async def route_interceptor(route: Route) -> None:
url = route.request.url
if any(pattern.search(url) for pattern in FORBIDDEN_PATTERNS):
await route.abort("blockedbyclient")
raise RuntimeError(f"Safety Violation: Blocked attempt to hit binding endpoint: {url}")
await route.continue_()
await page.route("**/*", route_interceptor)- Network Route Interception: All outbound HTTP requests pass through route interceptors that abort any endpoint matching binding, contract submission, or direct debit setup patterns.
- Terminal State Assertion: The workflow finite-state machine (FSM) marks the quote output screen (where policy premiums and deductibles are calculated and rendered) as a terminal state. Any further step transitions trigger an immediate runtime exception.
- Fail-Closed Artifact Dump: If a carrier portal renders an unexpected intermediate modal or changes navigation flow, the worker aborts immediately, records a full DOM snapshot and Playwright trace, and exits without clicking forward.
2. Resilient Browser Automation vs. Brittle RPA
Traditional enterprise RPA suites (e.g., UiPath) rely heavily on absolute XPath or visual coordinates that break during routine portal maintenance. We designed our headless Playwright drivers with resilient, multi-signal heuristics:
- Accessibility-Tree Anchors: Inputs are targeted using ARIA roles, input name attributes, and semantic form labels (
page.get_by_label("Data da Carta de Condução")), decoupling selector stability from CSS refactorings. - Dynamic Field Resolution: Portuguese carrier portals categorize vehicles through cascaded select elements (Make → Model → Version → Power/Displacement). The worker maps standard vehicle catalog codes to carrier-specific select option values using fuzzy string matching and normalized power ratings.
- Session State Isolation: Each carrier execution runs in an ephemeral, isolated browser context. Authentication cookies are recycled through secure storage to prevent repetitive login overhead while ensuring zero cross-session state leakage.
3. Constrained LLM Workflows for Portal Resiliency
A common failure mode in modern automation is treating LLMs as autonomous agents with open-ended tool calling. Delegating end-to-end browser navigation to an autonomous LLM loop leads to non-deterministic clicking, infinite scroll traps, and unacceptable latency.
Instead, we used a strict design pattern: the LLM observes and suggests; deterministic code validates and executes.
# workers/llm/resiliency.py
from enum import Enum
from pydantic import BaseModel, Field
class PageState(str, Enum):
QUOTATION_RESULTS = "QUOTATION_RESULTS"
INTERSTITIAL_BANNER = "INTERSTITIAL_BANNER"
SESSION_EXPIRED = "SESSION_EXPIRED"
CARRIER_SYSTEM_OUTAGE = "CARRIER_SYSTEM_OUTAGE"
UNKNOWN_STATE = "UNKNOWN_STATE"
class PageClassification(BaseModel):
state: PageState
confidence: float = Field(ge=0.0, le=1.0)
dismissable_selector: str | None = None
observed_carrier_error: str | None = None
async def classify_unhandled_page_state(
llm_client, screenshot_bytes: bytes, visible_text: str
) -> PageClassification:
"""
Called only when deterministic Playwright locators encounter an unknown screen.
Returns structured Pydantic output evaluated against an execution whitelist.
"""
return await llm_client.structured_predict(
model="gemini-2.5-flash",
schema=PageClassification,
image=screenshot_bytes,
prompt=(
"Classify the state of this carrier portal screen. "
"Identify if an interstitial modal or session timeout is blocking form completion."
),
)LLM inference is restricted to three high-leverage perception tasks that pure DOM heuristics handle poorly:
- Unhandled Screen Recovery: When a carrier updates an intermediary alert, cookie banner, or session timeout modal, deterministic selectors fail. Rather than aborting the pipeline, a multimodal vision call inspects the screenshot and DOM snippet. If the classification identifies an
INTERSTITIAL_BANNERwith a clear dismissal target, a deterministic click handler closes it and resumes the workflow. - Automotive Catalog Disambiguation: Portuguese vehicle registration certificates (Documento Único Automóvel) supply raw alphanumeric vehicle strings (e.g.,
"RENAULT MEGANE SPORT TOURER 1.5 DCI 115CV"), whereas carrier portals use proprietary, non-standardized dropdown variants ("Megane IV ST 1.5 Blue dCi Intens"vs."Megane IV ST 1.5 dCi Limited"). A zero-temperature structured LLM call maps the registry description to the exact portal select option in a single turn. - Multimodal Output QA Judge: Before any quote payload is marked as valid, an LLM Judge cross-references the extracted JSON fields against the raw browser screenshot or rendered PDF proposal. If the visual proposal shows a €500 deductible for own damage (Danos Próprios), but the DOM parser missed the column due to an unexpected layout shift, the Judge flags the run with
QA_FLAG: DEDUCTIBLE_MISMATCHand routes the proposal to the HITL quarantine queue.
4. Canonical Schema Normalization
Carrier outputs vary widely in format: some provide structured tabular DOM summaries, while others generate multi-page PDF proposal documents. Crucially, each carrier uses differing vocabulary to describe identical coverages.
The normalization layer extracts and maps these disparate values into a canonical data contract:
| Canonical Field | Carrier A Format | Carrier B Format | Carrier C Format |
|---|---|---|---|
third_party_limit_eur | "Capital RC: 50.000.000 €" | "Responsabilidade Civil Legal" | "RC Obrigatória (€50M)" |
own_damage_deductible | "Franquia: 4% (€800)" | "Danos Próprios: FQ 500 €" | "Opção C (2% Valor Venal)" |
glass_breakage_limit | "Quebra de Vidros: €1.500" | "QIV Incluída" | "Vidros: Sem Franquia / Máx €1.000" |
travel_assistance | "Assistência: VIP" | "Km 0 Completa" | "Ass. Viagem Nacional + Estrangeiro" |
For carriers that emit proposals solely as downloadable PDFs, the worker captures the binary payload, extracts text streams using pdfplumber, isolates the coverage schedule table via layout bounding boxes, and validates extracted numerical totals against checksum rules (Net Premium + Legal Charges + ASF Surcharge = Gross Annual Premium).
5. Human-in-the-Loop (HITL) Operational Queue
In regulated insurance workflows, an erroneous quote presented to a client risks customer churn and regulatory scrutiny. The platform avoids silent failures by computing a composite confidence score for every simulation run:
- Extraction Confidence: Are all mandatory coverage lines (RC premium, total annual premium, legal stamp taxes) present and numerically reconciled?
- Variance Anomaly Detection: Does the calculated premium deviate by more than 3 standard deviations from historical benchmarks for that driver age and vehicle bracket?
- Portal Status Health: Did the carrier return a transient disclaimer (e.g., "manual underwriting required due to vehicle age")?
Runs scoring below 98% confidence are diverted to the broker's operational dashboard:
[Quarantine Alert: Simulation #SIM-84920]
Carrier: Allianz Auto
Flag: Missing isolated glass breakage deductible in extracted table.
Action: Broker clicks [Inspect Screenshot] -> 1-click confirmation -> Normalized payload emitted.Brokers review side-by-side screenshots with highlighted bounding boxes, verify the extracted data with a single click, and allow the quote to pass down the pipeline.
Production Impact
The platform transformed the brokerage's operational throughput:
- Cycle Time: Reduced multi-carrier auto quote generation from 30–45 minutes of manual typing to under 90 seconds end-to-end.
- Throughput: A single broker team can process 10x higher quote volume during peak renewal periods without adding administrative headcount.
- Operational Safety: Maintained a 100% zero-emission record across thousands of automated quotation runs, with zero accidental policy bindings or billing discrepancies.
- Data Standardization: Normalized disparate underwriter formats into structured JSON ready for client-facing comparison summaries and CRM records.