Profile
Back to NewsBack
GitHub Trending 37 min
Reader Mode
anandapurva55/agentic-claims-adjudication-aws: Full-stack multi-agent AI for motor claims adjudication on AWS: Bedrock, Strands agents, QLoRA, RAG, MCP, AgentCore memory, guardrails, human in the loop. React, FastAPI, CDK.

anandapurva55/agentic-claims-adjudication-aws: Full-stack multi-agent AI for motor claims adjudication on AWS: Bedrock, Strands agents, QLoRA, RAG, MCP, AgentCore memory, guardrails, human in the loop. React, FastAPI, CDK.

15 hours ago

Agentic Motor Claims Adjudication on AWS: Full-Stack Multi-Agent AI with RAG, MCP, Memory, Guardrails, QLoRA Fine-Tuning and Human in the Loop

CI</a> CodeQL</a> Interactive demo</a> !Python !AWS !Strands !MCP !RAG !Guardrails !Cognito !WAF !CloudFront !DynamoDB !S3 !Secrets Manager !React !TypeScript !FastAPI !uv

Executive summary

When a car is damaged, a claims adjuster at the insurance company (the person who checks the claim) decides what to pay. That means going through the claim form, repair estimate, photo and policy wording, and a wrong call hurts either the insurer or the customer.

This project helps the adjuster do that. AI agents read the claim and check it against the policy, rules recommend approve, deny or refer along with the amount, and the adjuster makes the final call.

Four agents, orchestrated with Strands Agents, run on Claude and Amazon Nova models through Amazon Bedrock. Each has a defined role and only the tools it needs, with record and policy lookups through the Model Context Protocol (MCP) and policy clauses retrieved by RAG. Amazon Bedrock AgentCore Memory lets the agents recall lessons from adjusters' past corrections. We refined the prompts on 63 sample claims, then tested the system on 78 new ones.

Results

  • Accuracy: 98.7%, with the right recommendation on 77 of the 78 new claims.
  • Latency: 25 seconds for a typical claim (p50) and 43 seconds at p95.
  • Cost: about 5 US cents of AI usage per claim.
  • Security and resilience: none of our 29 attacks succeeded, including instructions hidden in a claim to force an approval.
  • Fine-tuning: QLoRA fine-tuning of an open model (Qwen2.5-3B) on Amazon SageMaker raised accuracy on unseen wording from 65% to 88% and cut missed claim denials from 17 to zero, for about 40 US cents of training.
  • Agents or one AI call: when all the facts are in the claim itself, a single call was just as accurate at about one fiftieth of the cost. Agents pay off mainly when facts must be looked up, such as past claims or a garage's history.
We built the whole system on Amazon Web Services (AWS). Key design decisions:
  • Rules make the recommendation, not the AI, because payments must be exact, the same facts must give the same result, and every step must be traceable.
  • A person approves every claim, because a wrong approval or denial has real consequences and someone must be accountable.
  • Model choice by evidence. A prompted managed model still scored higher (98%) and costs less to run at this volume, so it stays in the live system.
See it in action: interactive demo (AI agents are switched off there to save cost).

Contents

| Section | What it covers | |---|---| | Try it | An interactive demo in the browser, with no server and no cost | | Results at a glance | A live run, and the headline measurements | | Problem and scope | The problem, the user, and what is in and out of scope | | How a claim is decided | The flow from claim packet to human decision | | Solution architecture | AWS services, the three paths and the release pipeline | | Design principles | The rules that settled the design questions | | Design decisions | Each choice, the alternatives considered and what it costs | | Agents, MCP and memory | The Strands agent graph, MCP servers and two tiers of memory | | Document and image understanding | Bedrock Data Automation on forms and real damage photos, with measurements | | Retrieval-augmented generation (RAG) | Chunking, embeddings, metadata, retrieval and its evaluation | | Fine-tuning a small model with QLoRA | Method, results and when fine-tuning pays off | | Frontend: the workbench UI | React and TypeScript app with a live agent graph | | Human in the loop | The sign-off gate that the API enforces | | Security and red team testing | Threat model, defence layers and 30 attacks with controls | | Evaluation | Golden and held-out sets, an independent oracle, ablations and the quality gate | | Agents compared with a single call | A single call baseline, a free-form benchmark and a planted problem investigation test | | Cost, latency and observability | Telemetry lake, measured optimisations and alerting | | Deployment | Acceptance test, console evidence and deploy commands | | Operating the system | Capacity, limits, releases, alarms, failure modes and responses | | Issues found and resolved | Diagnoses and fixes | | Limitations | Open gaps and how to close them | | Next steps | Planned improvements across retrieval, ingestion, identity and the fine-tuning study | | Quick start | Run it locally | | Repository structure | Where things live | | Data sources and references | Datasets, policy wordings and papers |


Try it

An interactive demo of the app runs on GitHub Pages, with no server and no cost. The AI agents are switched off there to avoid cost, so each run replays the rule baseline on real claim data. A banner says so on every page. Everything else works, and the visitor does each step.

  1. Sign in. The demo opens on the same sign-in screen as the live site. A login page, laid out like Cognito's, then asks for a username and password. Any username works with any password that meets the real password rule: 12 or more characters, with upper and lower case letters, a digit and a symbol. A checklist under the password box turns from red to green as each rule is met. There is no sign up, as in the live system.
  2. Pick a claim in the queue. CLM-2026044 carries an injected instruction in its narrative, and CLM-2026043 needs a senior adjuster.
  3. Run the agents and watch the graph and the trace.
  4. Make the call in the Decision panel: accept, override or escalate. Then open your initials, top right, and switch to senior adjuster to try the approval rule above INR 200,000.
The demo data is saved from the real backend when the site is built. A small fetch layer in the frontend answers the app's calls from that data, so nothing is sent anywhere. Limitations lists what the demo leaves out.

Results at a glance

!A live run on the deployed system: Bedrock Data Automation and a vision model read the photo, agents use memory and MCP tools, risk signals appear, and a person decides

A live run on the deployed system. The photo is read at ingestion, an agent recalls a lesson from long term memory, the photo and the repair estimate disagree, and the recommendation waits for a person.

| Measure | Result | n | |---|---|---| | Decision accuracy on claims with wording the system had not seen | 98.7% (95% Wilson confidence interval 93.1% to 99.8%) | 78 claims in two held-out sets | | Decision accuracy on 124 free-form narratives written and labelled by other model families | Agent team 98.4% and a single model call 98.4% | 124 claims | | Unsafe approvals (a claim that must be denied, approved) | 0 on the golden set and on held-out set 2. 1 on held-out set 1, caused by a defect in the test data, analysed below. 1 each for the agent team and the single call on the free-form set | 63 + 78 + 124 claims | | Payable amount, exact match rate | 100% on the template sets. The rules engine also reproduces 20 hand-calculated boundary claims | 141 + 20 claims | | Red team attack success rate (ASR), hardened system | 0% (0 successful attacks) | 29 completed attacks (a model error ended the 30th) | | Guardrail prompt attack detection rate | 52% (15 flagged) | 29 attacks | | Investigation test, agent plus rule safety net: recall and false alarm rate | Recall 96% (69 of 72 planted problems). False alarm rate 13% (11 of 84 runs) | 28 cases, 3 runs each | | Policy retrieval with clause cards: Recall@1, Recall@3 (the default), Recall@5 and MRR@5. With one correct clause per question, Recall@k equals Hit@k | Recall@1 60.4%, Recall@3 79.2%, Recall@5 85.4%, MRR@5 0.70. Without cards: Recall@3 66.7%, Recall@5 77.1% | 48 questions | | Damaged parts found in photos: precision, recall and F1 score | Precision 0.87, recall 0.74, F1 0.80 | 70 photos | | Claim form extraction by Bedrock Data Automation: document level exact match | 92.1% (58 of 63 forms fully correct) | 63 forms | | Fine-tuned small model against a prompted managed model: exact match accuracy on all six flags | 88.0% against 98.0% | 150 narratives | | Model cost per claim | 0.046 to 0.049 USD at the baseline, 0.035 USD with the optimised configuration (measured twice) | 22 claims, twice | | End to end latency per claim: p50, p95 and mean | Baseline (deployed): p50 24.6 s, p95 42.9 s, mean 28.4 s. Optimised: p50 21.5 s, p95 33.1 s, mean 24.2 s | 22 claims, one at a time | | AI model calls per claim | 20.9 at the baseline, 18.5 optimised | 22 claims | | Throughput of one server | About 2 to 3 claims a minute, not load tested on AWS | | | Automated tests | 525 (465 Python, 60 frontend) | |

A single model call followed by the same rules engine matched or beat the agent team on every accuracy benchmark, at about one fiftieth of the cost. So the case for the agents does not rest on accuracy. It rests on what they add when the facts live in records. Agents compared with a single call sets out the evidence, including where the agents lose.


Problem and scope

An adjuster handling a motor claim reads a form, a repair estimate and a photo, compares them with the policy wording, decides whether an exclusion applies, and calculates what to pay. Much of the work is reading and cross-checking. The failure that matters most is a wrong approval: paying a claim that the policy excludes.

In scope. Reading the packet, retrieving the relevant clauses, judging the narrative against exclusions, calculating the payable amount, surfacing risk signals, and recording a human decision with an audit trail.

Out of scope. Paying claims, fraud adjudication, customer communication, and any decision made without a person.

Data. The claims are synthetic. The policy wording and the damage photographs are real.

Customer. The claims adjuster. The most important metric is the number of unsafe approvals. Accuracy, cost and latency matter less, but they are measured because they decide whether the system is usable.


How a claim is decided

A claim arrives as a claim form, a repair estimate, a short description of the accident and a photo of the damage. The steps below show what happens to it and which service does each part.

!Agent graph

  1. Ingest. The claim files sit in Amazon S3. Before any run, Bedrock Data Automation reads the form and the photo, and a vision model also reads the photo. The results are stored, so a run does not wait for them. The run loads them, compares Data Automation's reading of the form with a deterministic parser's reading, and flags any disagreement.
  2. Sign in and start. The adjuster signs in to the React app through Amazon Cognito and starts a run. The request passes through AWS WAF and Amazon CloudFront to the FastAPI backend on Amazon ECS with Fargate.
  3. Quarantine. The accident description and the other free text are written by the claimant or the garage. Bedrock Guardrails scan them, remove injected instructions and keep the legitimate facts.
  4. Intake agent. Strands Agents orchestrates the agents, which run on models from Amazon Bedrock. The Intake agent recalls lessons from Bedrock AgentCore Memory and records six judgement flags (intoxicated, commercial use, unlicensed driver, mechanical failure, tyre only, theft), quoting the sentence behind each. It understands negation.
  5. Coverage and Investigator agents run in parallel. They reach their tools through the Model Context Protocol (MCP). Coverage retrieves policy clauses, found by Bedrock Knowledge Bases over S3 Vectors (RAG), reads the policy schedule through the policy_records server and calls the payable calculator. The Investigator checks repeat claims through policy_records, and the garage record, benchmark repair costs and the police report through the claims_ops server, and records advisory risk signals.
  6. Bounded collaboration. Agents may post questions to each other. By default there is one round, with at most three questions.
  7. Photo check and rule checks. Code compares the parts the photo shows as damaged with the parts on the estimate and adds an advisory signal if they disagree. It also adds any finding the Investigator should have recorded and did not: a repair cost above its benchmark, a flagged garage, a repeat claim, a missing police report. Every signal carries its source, agent or rules.
  8. Adjudicator. The deterministic rules engine, written in Python, applies the rules in precedence order and produces the decision, the calculation and the next step. A model writes only the memo.
  9. Human adjuster. The recommendation appears in the app as it is produced. The adjuster accepts, overrides with a written reason, or escalates. Each claim gets exactly one human decision, stored in Amazon DynamoDB under the name and role from the sign in token. An override becomes a candidate evaluation case and a lesson in long term memory.
  10. Measure. Every model call is recorded with its tokens, time and cost. The records go to Amazon S3, where AWS Glue, Amazon Athena and Amazon QuickSight query and chart them. Amazon CloudWatch raises alarms on errors, slow responses and unusually costly runs.
If an agent does not finish, the claim is referred to a person with reason INT.AGENT. The system does not guess.

Solution architecture

!AWS architecture

| Path | Purpose | Services | |---|---|---| | Serving | Answer the adjuster | AWS WAF and Amazon CloudFront at the edge, Amazon Cognito for sign in, a CloudFront VPC origin to an internal Application Load Balancer, Amazon ECS on Fargate (arm64) running FastAPI and the agent graph | | Reasoning | Decide | Amazon Bedrock models, Guardrails, Knowledge Bases, Bedrock Data Automation, AgentCore Memory | | Learning and operations | Measure and improve | S3 telemetry lake, AWS Glue, Amazon Athena, Amazon QuickSight, Amazon CloudWatch, Amazon SageMaker |

| Service | Role in the system | |---|---| | Amazon Bedrock | Nova 2 Lite for the intake and investigator agents, Claude Haiku 4.5 for the coverage agent, and Claude Sonnet 4.6 for the adjudicator memo. Model identifiers are set in configuration | | Bedrock Guardrails | Prompt attack filter, hate and insult filters, PII handling, regex detectors for Aadhaar and PAN numbers, a denied topic for approval overrides | | Bedrock Knowledge Bases on Amazon S3 Vectors | Policy clause retrieval with Titan Text Embeddings V2 (RAG) | | Amazon Bedrock Data Automation | Reads the claim form and the damage photo into structured fields with two custom blueprints | | Bedrock AgentCore Memory | Short term notes per claim, long term lessons (semantic strategy) writable only by a human | | Amazon ECS on Fargate, internal ALB, CloudFront | Serving. The load balancer is internal and sits in isolated subnets with no route to the internet. The task runs in a public subnet, because there is no NAT gateway and the task calls AWS services. It accepts traffic only from the load balancer's security group. CloudFront reaches the load balancer through a VPC origin. The load balancer admits only the security group that CloudFront attaches to that origin, and its listener rejects requests that lack a secret header | | Amazon ECR | Stores the container image that the Fargate task runs | | React, TypeScript, Vite and FastAPI | The web app the adjuster uses, and the Python backend that runs the agents | | Amazon Cognito | Sign in. Only administrators create users. Two groups, adjuster and senior, set the reviewer's role. The site signs in through Cognito's hosted page, using the authorization code flow with PKCE | | AWS WAF | Rate limits per client address on CloudFront: 20 agent runs and 600 requests in 5 minutes | | AWS Secrets Manager | Generates the secret header value at deploy time, so it never appears in the repository | | Amazon DynamoDB | Four tables: policies, extracted claim data, the audit log, and run metrics | | Amazon S3 | Four buckets: claim files and Data Automation output, policy documents, the telemetry lake, and fine-tuning files. A separate S3 Vectors bucket holds the clause index | | AWS Glue, Amazon Athena, Amazon QuickSight | One JSON record per model call lands in S3. Athena queries it with partition projection. QuickSight shows cost and latency | | Amazon CloudWatch | Dashboard, latency and 5xx alarms, and a cost spike alarm fed by a custom metric | | Amazon SageMaker | QLoRA fine-tuning job on one GPU instance | | AWS CDK (Python) | Defines all the AWS resources as Infrastructure as Code, in two stacks: ClaimsAdjudicationData for the data and AI services, and ClaimsAdjudicationApp for the service, network and sign in. It runs without AWS credentials, so tests check the synthesised template in CI | | GitHub Actions | Workflows for lint, types, tests, the eval gate, the red team, CodeQL, the interactive demo, live evaluation and deploy. The Python environment comes from uv.lock. Deploy and live evaluation sign in to AWS through OIDC, using role ARNs stored as repository variables, so no long lived keys are stored | | CodeQL, Dependabot and GitHub Pages | CodeQL scans the code for security problems, Dependabot raises dependency updates and alerts, and Pages hosts the interactive demo |

Release path

The CI workflow runs on every push and pull request. It runs lint with the security rules, mypy, the Python tests, the replay quality gate, the red team in replay mode, the frontend tests, an npm audit, the type check and build, the infrastructure security tests, and CDK synthesis. The infrastructure job waits for the frontend build. A separate CodeQL workflow scans the Python and TypeScript code on every push. A third workflow publishes the interactive demo to GitHub Pages on every push to main. Deploy and live evaluation are manual workflows, and CI does not gate them. They need an OIDC provider and a deploy role that this CDK app does not create.

The diagrams are written as code with the Python diagrams library (docs/diagrams/generate.py). They are versioned with the system, and tests check the facts they show.


Design principles

These principles settled the design questions below.

  1. Models judge, code decides. A model sets six judgement flags. A tested rules engine turns the flags and the facts into a decision and a payable amount. A model that is manipulated can change a flag, but it cannot set an amount.
  2. A person owns every outcome. The API refuses to settle a claim without a recorded human decision. The UI is not the control.
  3. Customer text is hostile. Narratives and garage remarks are treated as data, not instructions. A guardrail scans them before any agent reads them. No agent has a tool that pays money.
  4. Least privilege, including for memory. Each agent receives only the tools it needs. Long term memory is writable only by a human.
  5. Measure against a baseline, on data not tuned against. Every claim of improvement states its baseline, its sample size and its uncertainty.
  6. Report what failed. Defects, retracted conclusions and open gaps are part of the result.

Design decisions

| Decision | Alternatives considered | Rationale | Cost of the choice | |---|---|---|---| | A rules engine decides, models set flags | Let an agent decide and calculate | Money and exclusions need exact answers and resistance to injected text. Given correct flags, the engine reproduces all 63 golden outcomes and 20 hand-calculated boundary claims exactly | The engine must be updated when the policy changes. Situations it does not cover go to a human and are not guessed | | ECS on Fargate | EC2, Lambda | No servers to patch, scales per task, and costs nothing when scaled to zero. Agent runs last 20 to 40 seconds and stream their progress, so a long lived container suits them better than Lambda | Live runs are serialised per task, because tool state is per process. Scaling out means more tasks | | S3 Vectors | OpenSearch Serverless, pgvector | The corpus is small, and S3 Vectors has no standing hourly charge | No hybrid (keyword plus vector) search | | Public subnets for tasks, isolated subnets for the load balancer, no NAT gateway | Private subnets with NAT | Saves roughly one dollar a day for a workload with no private resources. The load balancer is internal, so it has no public address at all, and tasks accept traffic only from it | Tasks have public IPs. Acceptable here, not for a regulated workload | | CloudFront reaches the API through a VPC origin to an internal ALB | A public ALB limited by CloudFront's prefix list and a secret header. HTTPS to the origin, which needs a certificate and a domain name | Traffic never crosses the public internet. The load balancer can be reached only through CloudFront. No domain has to be bought. The secret header stays as a second check | More moving parts: CloudFront attaches its own security group to the origin's network interfaces, and the load balancer has to admit that group by id (see issues found and resolved) | | Cognito hosted sign in, authorization code flow with PKCE | A login form in the app, a shared API key | No password passes through the application, tokens never appear in a URL, and the role is a group inside a token that the API verifies | The sign in page is Cognito's, styled with its branding settings. Administrators create users | | Python dependencies locked with uv | pip and requirements files | uv sync rebuilds the exact environment CI tests, down to the hash of every package. A warm install took 1 second against 27 for pip on the same requirements | Contributors need one extra tool | | Bedrock Data Automation for documents | A local PDF parser, Amazon Textract | Managed, handles forms and images with one project, custom blueprints give typed fields. A deterministic parser runs beside it as an independent second reader | 15 to 30 seconds per job, so it runs at ingestion, not on click. Two readers can disagree, which is the point of the check | | Two MCP servers, stdio | Direct function calls | One protocol for tools. The same servers can be reused by another agent. Tool access is scoped per agent | Process startup per run | | Human write only long term memory | Let agents store lessons | Closes the memory poisoning route | Lessons arrive only through human review and seeding | | Model identifiers as configuration | Hard coded models | The account's Bedrock quotas are small and differ per model, so the system spreads models across quotas and can swap them | Behaviour depends on which models are configured, so evaluations record them |


Agents, MCP and memory

Strands agent graph. Intake, Coverage and Investigator are the nodes of a Strands graph: Intake runs first, then the other two in parallel. The Adjudicator is a fourth agent that runs after the graph and the rule checks. Each of the four agents is a Strands Agent with its own system prompt, tool list and Bedrock model, and each MCP server is attached to the agents that need it through Strands' MCP client. Strands does the orchestration of the graph. The rest is Python code in the runner: the rule and photo checks, the one round of questions that agents may ask each other after the graph finishes, and the call to the rules engine that decides. Hooks emit an event for every model call, tool call and handoff, and the animated graph in the UI is drawn from that stream, so every pulse corresponds to something that ran. A call budget of 40 model calls per run bounds a runaway agent.

MCP servers. Two servers expose tools over stdio: policy_records (policy wording search, schedule, claim history) and claims_ops (garage check, repair cost benchmark, police report verification). Each agent receives only the tools it needs, and no tool pays money, edits a policy or reaches another customer.

Findings the agent does not record. An agent is asked to record what it finds, but a model sometimes describes a finding without calling the tool that records it. The investigation test (below) showed this. In a traced run, the Investigator received a flagged garage with six flagged estimates. Its summary said it had recorded a medium risk signal, but it never called record_risk_signal, so the adjuster would have seen nothing. Across the 9 single-finding garage runs, it recorded none. The run therefore ends with add_rule_signals. It adds every finding that the rules can reach and the agent did not record, keeps the agent's own signals, and recognises a second inflated repair line when the agent flagged only the first. On the 84 stored agent runs, exact matches rose from 62 to 73 at no extra cost. This guarantees that the findings the rules can reach are delivered. It does not make the agent better at judgement, which is what the agent is for.

Memory in two tiers.

| Tier | Holds | Written by | |---|---|---| | Short term (AgentCore events) | Agent to agent notes for the current claim | Agents | | Long term (AgentCore semantic memory) | Lessons from senior adjusters and from overrides. For example, "a few drinks" or "whiskeys" mean the driver was intoxicated, even without the word alcohol | Humans only |

Effect of memory and collaboration. Removing either one brought back one specific failure on the hard cases (see ablations). Without memory, a claim describing "whiskeys at a wedding" was approved in 1 of 3 runs. Without collaboration, a claim about a parcel from a friend was wrongly denied in 2 of 3 runs. These are single claims with few repeats. They show where to look and do not prove a mechanism.


Document and image understanding

Amazon Bedrock Data Automation turns unstructured files into structured fields. One project holds two custom blueprints.

| Blueprint | Input | Fields | |---|---|---| | claims-adjudication-motor-claim-form | Claim form PDF | claim id, policy number, holder, registration, incident and report dates, police FIR, claimed amount, narrative | | claims-adjudication-vehicle-damage-photo | Damage photo | is_vehicle_photo, damaged_parts, severity, description |

Jobs are asynchronous and take 15 to 30 seconds, so they run as an ingestion step and not when an adjuster opens a claim. Ingestion is a batch script here, and an S3 event would trigger it in production. Results are stored with the claim (DynamoDB in AWS, files locally), and the agent run reads them. scripts/run_bda_ingest.py processes every file and scores the output.

!Bedrock Data Automation blueprint tested on a real damage photo in the console

Claim forms. At run time, the form fields come from a deterministic parser, because the generated PDFs have a known layout. Bedrock Data Automation reads the same forms independently, and a disagreement between the two readers raises an advisory signal. Across 63 forms, claim_id, policy_no, vehicle_reg, incident_date, report_date and claimed_amount were 100% correct. holder was 92.1% correct. The five misses are one surname: the OCR read "Iyer" as "lyer". 58 of 63 forms were fully correct. The five holder-name misses reach the adjuster as low severity signals.

Damage photos. The photos are real: 70 photographs from the public Kaggle Coco Car Damage Detection Dataset (CC0), annotated with the damaged parts (headlamp, front bumper, rear bumper, hood, door). scripts/attach_real_photos.py gives each claim the unused photo whose damaged parts best match the parts on its estimate. 44 of 63 claims receive one. The other 19 list only parts outside those five, and the UI says so. The annotations let the reading step be scored against ground truth on all 70 photos:

| System | Precision | Recall | F1 | |---|---|---|---| | Bedrock Data Automation plus Claude Haiku 4.5, union (used) | 0.87 | 0.74 | 0.80 | | Claude Haiku 4.5 | 0.86 | 0.68 | 0.76 | | Claude Sonnet 4.6 | 0.94 | 0.61 | 0.74 | | Nova 2 Lite | 0.93 | 0.59 | 0.72 | | Bedrock Data Automation, revised blueprint | 0.95 | 0.51 | 0.66 | | Bedrock Data Automation, first blueprint | 0.96 | 0.44 | 0.60 | | Intersection of BDA and Haiku | 0.95 | 0.45 | 0.61 |

Bedrock Data Automation is cautious. When it names a part, it is right 95% of the time, but it finds only about half of the labelled parts. Its blueprint instruction was revised once. It was then evaluated on the half of the photos that were not examined while editing, and F1 rose from 0.64 to 0.69. Combining it with a vision model recovers most of the missing recall. The union rule was fixed before it was scored, and nothing was tuned. On the held-out half, F1 is 0.82 for the union, 0.80 for Haiku alone and 0.69 for Data Automation alone. The product therefore reads each photo with both and uses the union. The extra cost is one vision call per photo at ingestion.

The photo never changes the decision. It only produces an advisory signal. A false alarm costs the adjuster a glance, and a miss changes nothing about payment.

!Claim packet with the real photo and the parts detected


Retrieval-augmented generation (RAG)

Policy wording is retrieved at run time and cited. It is not placed in the prompts. The retrieval layer has one job: to return the clause where an exclusion is written, with an identifier that the adjuster can check.

| Stage | Choice | Reason | |---|---|---| | Corpus | Three insurers' private car package wordings (PDF), plus 16 clause cards | Cards are one short document per clause: 12 verbatim policy clauses and 4 internal controls | | Chunking | Fixed size with 20% overlap. 150, 300 and 800 tokens compared. Cards are ingested as separate documents at 500 tokens | Clauses are short and cross-referenced, so chunk boundaries decide whether an exclusion and its condition stay together | | Metadata | A sidecar file per card carries clause_id and origin, and it is returned with every hit | The agent cites SEC1.EXCL.1c, not a page number | | Embeddings | Amazon Titan Text Embeddings V2, 1,024 dimensions, float | One model for chunks and queries | | Index | Amazon S3 Vectors, one index per knowledge base | No standing hourly cost for a corpus this small | | Retrieval | Approximate nearest neighbour, top 3 by default, exposed to agents as the MCP tool search_policy_wording | The agent can request more | | Grounding | The coverage agent reasons over the returned text and cites clause identifiers | The rules engine decides, so retrieval is not on the payout path |

Evaluation. 48 questions, each tied to the clause that answers it and phrased the way an adjuster or customer would ask, not in the policy's words. A question counts as a hit if its clause is in the top k results. Each question has one correct clause, so Recall@k here is the same as Hit@k. MRR@5 (mean reciprocal rank) is higher when the correct clause ranks nearer the top. Four configurations were compared on the same questions:

| Configuration | Recall@1 | Recall@3 | Recall@5 | MRR@5 | |---|---|---|---|---| | 300 token chunks | 35.4% | 66.7% | 77.1% | 0.52 | | 150 token chunks | 52.1% | 66.7% | 72.9% | 0.60 | | 800 token chunks | 45.8% | 68.8% | 70.8% | 0.56 | | 300 token chunks plus clause cards | 60.4% | 79.2% | 85.4% | 0.70 |

Compared with 300 token chunks, both 150 and 800 token chunks gave better Recall@1 and worse Recall@5. Clause cards improved every measure, so the product uses them. The operating point is Recall@3, because the tool returns 3 chunks by default. With plain chunks, the weakest topics were coverage ("is a flood covered?"), tyres and mechanical failure, where the customer's words and the policy's words share few terms.

Trade-offs and failure modes.

  • S3 Vectors has no hybrid (keyword plus vector) search, which is the usual fix for that vocabulary gap. A managed search cluster would add it at a standing cost that a corpus this size does not justify.
  • A retrieval miss weakens the explanation and the citation. It cannot change a decision or a payout.
  • Ingestion allows one concurrent job per knowledge base, so the deployment runs them in sequence. Changing the embedding model means re-ingesting, which is cheap because the index is rebuilt from S3.
  • 48 questions over 12 clauses rank the configurations. They do not establish production recall.

Fine-tuning a small model with QLoRA

Objective. Test whether a small open model, fine-tuned cheaply, can set the six judgement flags (intoxicated, commercial use, unlicensed driver, mechanical failure, tyre only, theft) as well as a prompted managed model, and say when each is the right choice. The work is in finetune/.

Model. Qwen2.5-3B-Instruct, a decoder-only transformer with 36 layers, hidden size 2,048, 16 attention heads using grouped-query attention (2 key-value heads), an 11,008-wide feed-forward block, a 151,936-token vocabulary and 3.09 billion parameters (read from the model's own configuration). Decoding is greedy, so results are repeatable.

Method.

| Aspect | Setting | |---|---| | Adaptation | LoRA on all linear layers (query, key, value, output, gate, up, down) in all 36 layers. Rank 16, alpha 32, dropout 0.05. 29,933,568 trainable parameters, which is 0.97% of the model, saved as a 60 MB adapter in 16 bit. The adapter starts at zero, so training starts exactly from the base model. After training, it can be merged into the weights with no extra cost per token | | Quantisation (QLoRA) | The frozen base model is stored in 4-bit NF4 with double quantisation, and computation uses bfloat16. The base weights shrink from about 6.2 GB to about 1.5 GB, so training fits on one 24 GB A10G. On a Mac without CUDA, the script uses plain 16-bit LoRA for smoke tests | | Objective | The loss counts the answer JSON only (completion_only_loss), so the model is not scored on copying the narrative. Prompts and answers use the model's own chat template, the same for every system compared | | Optimisation | Learning rate 2e-4, cosine schedule, 3% warm-up, 3 epochs, effective batch size 16 (8 per step, 2 accumulation steps), maximum length 512, gradient checkpointing | | Libraries | Hugging Face Transformers, PEFT, TRL SFTTrainer, bitsandbytes | | Compute | One ml.g5.2xlarge (NVIDIA A10G, 24 GB) SageMaker training job. It was launched with plain boto3, used a dedicated bucket and a least-privilege execution role created by CDK, and had a 90 minute hard stop. Training took 427 s, and 968 seconds were billed in total, which is about 40 US cents (an estimate from billable seconds and an assumed on-demand rate) |

Data and splits. Narratives are generated from phrase banks. Each has a base accident sentence, zero to two sentences that state or deny a flag, and filler. The denials and traps are the point, for example "had not consumed any alcohol", "a parcel that a friend had sent" and "a tyre burst and the car then hit a divider". The train set has 1,200 narratives and the dev set has 150, both from the training banks. The unseen test has 300 narratives from different banks, so every sentence in it is wording the model never saw. Tests check that no sentence is shared and that every label follows from the text. A further 63 narratives come from the claims system itself. They are a secondary result only, because 39 of the 63 share a sentence with the training phrases.

Results. The same 150 held-out narratives and the same scoring code were used for every system:

| System | Exact match (all 6 flags) | Missed denials | |---|---|---| | Claude Haiku 4.5, 4 examples | 98.0% | 0 | | Claude Sonnet 4.6, 4 examples | 96.7% | 0 | | Claude Sonnet 4.6, zero-shot | 92.7% | 0 | | Claude Haiku 4.5, zero-shot | 89.3% | 0 | | Qwen2.5-3B with QLoRA | 88.0% | 0 | | Nova 2 Lite, 4 examples and zero-shot | 82.7% and 76.7% | 0 and 0 | | Qwen2.5-3B prompted, 4 examples and zero-shot | 68.0% and 65.3% | 3 and 17 | | Keyword baseline | 49.3% | 38 |

With 150 narratives, the 95% uncertainty on an accuracy near 88% is about 5 points, so neighbouring rows are not meaningfully different. On the full 300 narratives, the tuned model scored 89.3% and the untuned model 59.7%. About 60% of the untuned model's zero-shot answers were not valid JSON.

Findings.

  • Fine-tuning worked as a technique. On unseen wording, accuracy went from 65% to 88%, and missed denials, the dangerous error, went from 17 to zero. The remaining mistakes are false denials, which an adjuster would see and correct.
  • It does not pay off for this product. Prompted Haiku scores 98% for roughly 500 input and 40 output tokens per call, which is about 0.07 US cents, and it needs no GPU. The tuned model processed a narrative in 0.26 s in GPU batches, which is about 0.011 cents at full use. But an always-on endpoint costs on the order of 1,100 US dollars a month whether or not it is used. The API costs well under a dollar a month at roughly a thousand claims a month. These cost figures are estimates from token counts and list prices. Fine-tuning wins at very high steady volume, when data must stay in the account, or when no strong hosted model exists.
Limits. Errors cluster. 17 of the 32 wrong narratives (of 300) come from one unseen sentence ("The driver handed over a current licence when asked", read as unlicensed), and 6 more come from one engine failure paraphrase. The 300 narratives contain only about 60 distinct unseen sentences, so they overstate the evidence. Training loss fell to about 0.00001 by epoch 1.6. The dev loss is just as small, because dev shares phrase banks with train, so only the unseen wording test can show overfitting. This is one run with one seed, with no hyperparameter search, on synthetic text.

!SageMaker training job record


Frontend: the workbench UI

The frontend is a React 19 and TypeScript single page application built with Vite. It starts a claim run with a POST and reads the server-sent event stream from the response with fetch, because EventSource can only send GET and cannot carry the sign in token. It draws the agent graph as hand-written SVG animation, so each node and pulse corresponds to an event emitted by a Strands hook or a service call. It is served from S3 through CloudFront, and the /api path is routed to the backend.

Signed out visitors see the sign in screen. The form is on the left, and a fixed example of the review card is on the right, so a reviewer sees what they are about to work with. The button sends them to Amazon Cognito's managed login page, which is styled to match: dark, with the same wordmark and buttons, and the same example card as its background. It uses the authorization code flow with PKCE. They return with a code that is exchanged for tokens, and the address bar is cleaned. The ID token is refreshed before it expires and sent on every call. A cookie scoped to the read-only file path lets the evidence photo load, because an image tag cannot send a header. When the site has no sign in configuration, as in local development, the sign in screen is skipped and a demo role selector appears.

!The sign in screen, shown to a signed out visitor

!Cognito's managed login page, styled to match the app

!Signing in: the app's screen, Cognito's page, the credentials, and the workbench with the account menu

Passwords. Sign up is off. An administrator creates each account, and its group sets the role. The sign in screen says so: there is no sign up, and an administrator provides the credentials. Someone without an account sees a "Request access" link. It writes to an address that is set at build time. On the Pages site, the address comes from the repository variable REQUEST_ACCESS_EMAIL, so it is kept in the repository's settings and not in the code. "Forgot your password?" sends a code by email. That needs a verified email address on the account, so administrators create users with one. A user created without an email cannot reset a password.

!The forgot password page

!The reset code email, as Cognito sends it

!Workbench mid run, live

  • Workbench. Claim queue with filters, the live agent graph, the claim packet with the photo and detected parts, a reasoning trace, and the decision panel with checks, calculation, clause citations, risk signals, recalled lessons and review controls. The header shows the signed in person's initials, and their menu gives the name, the role from the token (which is what the four eyes rule uses), what that role may approve, and sign out.
!The account menu: name, role and approval limit
  • Architecture. The agent graph, drawn statically, with the design principles.
  • Security. The attack lab, red team results and defence layers.
  • Observability. Cost, latency, where the money goes, alert rules and review statistics.
!Decision panel with risk signals, memory and the sign-off gate

!Architecture tab

The mode chip shows whether the deployment runs the offline baseline or live agents on Bedrock.

Tests. 60 Vitest tests cover the PKCE challenge against the test vector in RFC 7636, token decoding and role mapping, the server-sent events parser (including every way a stream can be cut into chunks, and the queue position events), the API layer against a fake server, and the interactive demo's review rules, sign in and Try it steps. Five planted bugs, among them a GET where the run should be a POST, were each caught. A headless browser run against the built app checks the same flow end to end: the run streams, the review is recorded under the right identity, the photo loads and the console stays clean.


Human in the loop

The AI recommends and a person decides. The API enforces this, so it cannot be bypassed by calling an endpoint directly.

!The human sign-off gate: an adjuster is blocked above the authority limit, a senior adjuster signs in through Cognito and accepts, and the decision is logged

| Rule | Mechanism | |---|---| | Nothing is settled without a human | A claim moves new, AI recommended, reviewed. The only exit from AI recommended is a recorded human decision. Reviewing before the agents ran returns 409 | | Four eyes | A payable above INR 200,000 can be approved only by a senior adjuster. Overriding a denial or a referral to approve also needs a senior adjuster at any amount, because those outcomes have no payable and so carry no limit. An adjuster receives 403 and can always escalate, refer or deny. A senior's override to approve records no payable, and the outcome says the amount must be set before payment | | Overrides need a reason | An override carries a final decision and a written reason of at least 10 characters, stored beside the AI recommendation | | A review names the run it looked at | Every review carries the id of the run the reviewer was shown. The API refuses the review with 409 if the latest recommendation has a different id. So "accept" always means the result on screen, and not a newer result that a colleague produced a moment later. A recommendation from a different mode than the deployment's, or one that has no run id, cannot be approved either | | One decision per claim | A conditional DynamoDB write allows exactly one human review per claim. If two reviewers decide at the same moment, one succeeds and the other gets 409. This is tested with eight concurrent writers and was mutation checked. The task's role can add rows to the audit table but cannot update or delete them, and this is checked on the deployment template. The audit trail cannot be overwritten, even with several tasks running | | Attributable | Each record holds who decided, their role, the AI recommendation and clauses, the final decision and the outcome. The name and role come from the sign in token and never from the request body, so a caller cannot promote themselves by editing the JSON | | Never a dead end | Every referral names the next action: a senior adjuster, resubmitted documents when form and estimate disagree, a delay investigation, a police report for theft | | Disagreement becomes data | An override is saved as a candidate evaluation case and as a lesson in long term memory |

The audit log is stored in DynamoDB, which is the single source of truth. Every task reads it directly, so scaling out cannot split it. Listing the claims takes one read of the log, not one read per claim.


Security and red team testing

Red team testing means attacking the system on purpose, as a malicious claimant or garage would, and counting what gets through. It complements the functional tests.

Threat model. The attacker is a claimant or a garage who controls the narrative, the remarks or a document. Goals: get an excluded claim approved, make the system reveal a secret (identifiers, prompts, another customer's data), misuse a tool, or plant a rule in memory.

| Layer | Control | |---|---| | 1. Input guardrail | Bedrock Guardrails scans the narrative and the free text fields of the form and the estimate (holder, garage, police reference, line names) for prompt attacks. A flagged field is replaced as a whole. If a whole text is blocked, each sentence is checked alone so only offending sentences are removed | | 2. Data, not instructions | Prompts state that the narrative is data. Instructions inside it are reported, never followed | | 3. Least privilege tools | Each agent reads only the claim in front of it. No tool pays money, edits a policy or reaches another customer. The task role names its models, guardrail and tables. Two permissions use a wildcard: the region in foundation model addresses, which global inference profiles need, and the CloudWatch metrics call, which AWS requires and which is limited to one namespace | | 4. Code decides | Agents set flags and an engine decides, so a hijacked agent cannot produce a payout | | 5. Memory is human write only | Agents recall lessons and cannot write them | | 6. Human in the loop | Every recommendation is reviewed and logged | | 7. Sign in and input limits | Every route except the health check needs a valid Amazon Cognito ID token. The API checks the token's signature against the pool's keys, and its issuer, audience, expiry and type. A caller in no group gets 403. Review actions, decisions and run modes are fixed values, free text has length limits, and the reviewer's name is cleaned before it reaches the audit log | | 8. Private network | The load balancer has no public address. CloudFront reaches it through a VPC origin, and its security group admits only the group CloudFront attaches to that origin. The task role names the three models, the guardra

... (README truncated for length)

Chat with me