← VetCare One for clinics

How VetCare One is built

A case study of the system behind the product: how a single backend enforces five access modes, how the assistant decides where each question goes, the three forecasting models and their error bars, the data model, testing, and what broke along the way.

What it is

A clinic system first. An AI system second.

VetCare One was built for Pro Pet Animal Hospital, a single-site veterinary clinic in Sri Lanka, to replace paper files and spreadsheets with one system covering the clinical and commercial side of the practice.

It was then extended during an eight-week AI Launchpad programme with two additions: a retrieval-augmented AI assistant grounded in the clinic's own data, and a native iOS app that gives pet owners and prospective clients their own self-service access.

Every AI feature is positioned the same way: decision support for a qualified veterinarian, never a replacement for one.

5Access modes — guest, pet owner, receptionist, vet, admin
4Predictive modules — disease, sales, inventory, pet health
3Local AI models — embeddings, text and vision
0Clinic records sent to a cloud AI provider
Try it

Same question, five different people

Pick who is asking and what they ask. The answer changes, and so does the route the question takes through the system. That route is decided by the server from the login, never by the app.

Signed in as

Ask

VetCare assistant · playgroundReceptionist
Route

These are scripted replays that follow the system's real routing and role rules. Pet names, counts and figures are illustrative, not captured output. The row below is captured output.

Captured live · the same question, three logins

Screenshots

See it running

Captured from the live system against the clinic's demo database, with the assistant answering on the local model — nothing here is a mock-up.

Admin dashboard with an AI daily briefing, total collected, outstanding payments, today's appointments, low-stock alerts and a per-vet appointment table.
Admin dashboard. The AI daily briefing summarises revenue drivers, reorder alerts and outbreak trend from the live models; the tiles below it come straight from the database.

On iPhone

The native SwiftUI app gives owners the same portal, calling the same backend under the same access rules.

iOS home screen greeting the owner, listing their two pets, Loki and Max, with cards for appointments and the AI assistant.
HomeThe owner's pets, appointments and AI tools in one place.
iOS pet detail for Max showing age, weight, sex, date of birth, a penicillin allergy note and vaccination due dates.
Pet detailProfile, allergies and vaccination due dates.
iOS assistant asked what vaccines my pet has had; it asks whether the owner means Loki or Max, then lists Loki's vaccinations with citations to the pet's records.
AI assistantScoped to the owner's own pets — it asks which pet, then cites the records it used.
iOS AI Visual Care result describing red spots on a dog's skin, stating it cannot diagnose, giving care steps and advising a vet visit.
AI Visual CarePhoto guidance that says plainly it can't diagnose, and when to see a vet.

Demo data only. Web screens captured at 1440 px; iOS screens from the iPhone simulator.

Every module

The rest of the web portal

Front desk, clinical, billing, inventory, analytics and administration — each screen from the running system. Click any screen to enlarge it. Contact details are blurred.

Front desk & clinical

Billing & inventory

Analytics & insights

Administration

Who sees what

The assistant only knows what you're allowed to know

Access is decided by the server from your login, and enforced again inside the database query — never trusted to the app or the AI model.

CapabilityGuestPet ownerReceptionistVetAdmin
General pet-care answers & clinic FAQsYesYesYesYesYes
Own pets, appointments and balanceNoOwn onlyYesYesYes
Book, reschedule & register by chatNoNoYesYesYes
Billing — invoices & paymentsNoOwn balanceYesView onlyYes
Clinical drafts & diagnosis detailNoNoNoYesYes
Pet health & outbreak riskNoNoNoYesYes
Register staff membersNoNoNoNoYes

Summary of role boundaries across the app and the assistant.

What makes it different

Designed so the AI can't quietly get it wrong

Most "AI-powered" tools hand the question to a language model and hope. VetCare One routes each question to the part of the system that can answer it reliably, and uses the model only where language is the actual job.

Privacy

Runs on the clinic's own machine

All AI inference runs locally through Ollama. Medical histories and owner contact details never leave the premises, and there's no per-question cost or API key to manage.

Accuracy

Counts come from SQL, not guesses

"How many appointments today?" is answered with a real database query. A language model only ever sees a small sample of records, so it's never asked to total them up.

Completeness

Full histories, not samples

A patient history summary fetches every relevant record by SQL and hands the complete set to the model — so a "full history" is never a partial one presented as complete.

Control

Nothing changes without a yes

The assistant proposes bookings, registrations and reminders; a person confirms them. Generated clinical notes are drafts, and no email goes out without review.

Reliability

The model parses, it never decides

The model turns free text into structured fields. Every pet, owner, vet and date is then resolved by database lookup — and when a name is ambiguous, it asks rather than picks.

Safety

It never diagnoses

Forecasts and risk scores are labelled as estimates. The guest assistant never names a medicine. Every answer points back to a qualified veterinarian's judgement.

Predictive models

Three trained models, with their error bars shown

Each model trains on the clinic's demo database: seeded data from January 2024 to September 2026, not real patient records. The figures below come from the latest training run in September 2026. Where the numbers are weak, this section says so.

Disease prediction

Random Forest · K-Means · Prophet

Data
389 disease cases across 8 categories and 21 species, mostly dogs (234) and cats (96).
Features
Species, breed, severity, age at diagnosis, treatment duration and a contagious flag. The model predicts the disease category.
Why these
A Random Forest copes with mixed categorical and numeric features on a few hundred rows without much tuning. K-Means (k = 3) groups similar case profiles. Prophet forecasts monthly case counts with yearly seasonality.
64.1%held-out accuracy, stratified 80/20 split
60.6%5-fold cross-validated accuracy
32.6%baseline: always guess the most common category
0.35silhouette score for the three clusters

Limits. The model is about twice as good as guessing, but nowhere near diagnostic grade. Three categories (neoplastic, genetic, nutritional) have fewer than 16 examples each. Its output is a starting point for an examination, never a diagnosis.

Sales forecasting

Prophet · Random Forest

Data
650 invoices, giving revenue on 404 billing days and 30 monthly totals.
Features
Prophet models daily revenue with yearly, weekly and monthly seasonality. The Random Forest predicts monthly revenue from the month, the quarter, a holiday-season flag, cyclic month encodings, three monthly lags, a three-month rolling mean and the transaction count.
Why these
Revenue has a yearly shape, with a December dip in both years, and many days have no billing at all. Prophet handles gaps and seasonality on short histories and returns an uncertainty interval.
Rs 35.5kcross-validated monthly error (MAE), against a Rs 92.8k average month
0.28R² on six held-out months
Rs 3.0kProphet daily error over the last 30 days held out
30months of history available to learn from

Limits. Revenue is recorded on only about 40% of days, so a single day's prediction is close to noise. The error on a month is about 38% of an average month. The app's forecast band is ±60%, the historical month-to-month variation, and it is shown on screen rather than hidden. Read the direction, not the exact figure.

Inventory demand

Gradient Boosting

Data
235 stock items and 75 consumption records at the last training run.
Features
Category, current stock, reorder level and quantity, unit cost, average and spread of daily demand, demand trend and days observed. The model predicts demand over the next 30 days.
Why this
Boosted trees capture the non-linear interplay of usage, stock and cost on small tabular data, and they produce the reorder suggestions and restock dates shown in the app.
14.5cross-validated error (MAE), in units of 30-day demand
235items scored on every run
75consumption records behind the usage features
100trees, depth 4, learning rate 0.1

Limits. Most items have little recorded usage so far. The training target is itself a projection (average daily use × 30, adjusted for trend) rather than observed next-month consumption, so for now the model smooths a heuristic instead of learning from real outcomes.

Revenue forecast, from the real model

This is the model's own output on the demo data. The monthly totals and the ±60% band follow the same aggregation as the app's Sales Forecasting screen. Drag to change the horizon, and hover for values.

Actual monthly revenue Prophet forecast Forecast band (±60%)
Show the data as a table
MonthActual (Rs)Forecast (Rs)Band (Rs)

September 2026 is a partial month: the data ends on 12 September. The March 2026 spike is in the source data.

The real-time risk engine

The pet health predictor is not trained. It computes four scores live from rules and from breed predisposition tables compiled from veterinary literature, so it works from day one. The trade-off is that it doesn't learn from the clinic's own outcomes. These are the calculations as the code runs them.

1 · Disease recurrence

Uses only this pet's own history. The more often a category has recurred, the higher the 12-month risk, scaled linearly to other horizons.

n = past cases in the category p₁₂ = 0.25 (n=1) · 0.45 (n=2) · min(0.25+0.15n, 0.80) p(t) = min(p₁₂ × t/12, 0.90) t ∈ {1, 6, 12, 24} months

2 · Cancer and tumour

A breed baseline (species baseline if the breed isn't listed) scaled by an age multiplier. It returns per-type risk and screening suggestions.

risk = min(breed_base × age_factor, 0.95) age_factor (dog, cat): <2y 0.1 · <4y 0.3 · <7y 0.7 · <10y 1.5 · 10y+ 2.5 high ≥ 50% · medium ≥ 25%

3 · Outbreak trend

Compares the last eight weeks of cases with the eight before, then projects forward with dampened growth.

g = (mean last 8 wks − mean prior 8 wks) / prior rising if g > 15% · declining if g < −15% cases(w) = base × (1 + g/4)ʷ

4 · Pandemic potential

An R₀-style estimate over the last 12 months. It weighs how contagious the caseload is, how many transmission routes appear, and how many species are affected.

R₀ ≈ contagious_rate × (1 + 0.3 × transmission_routes) × (1 + 0.5 × (species_affected − 1)) high ≥ 2.0 · medium ≥ 1.0

Cancer and tumour risk

——

Suggested screening

    Recurrence risk for that category

    Runs the same tables and formulas as pet_health_predictor.py, in your browser. This is decision support for a vet, not a diagnosis.

    Inside the assistant

    Retrieval is the last resort, not the first

    Most questions never reach vector search. A question passes through a fixed chain of handlers, and the first one that can answer it reliably takes it. Search only gets whatever is left.

    Live-model gatesml/app.py

    Outbreak risk, disease trend, revenue forecast and reorder questions from admins and vets go straight to the trained model. Receptionists get a clear "not for your role". For guests and owners, the same words ("what should I do in an outbreak?") are ordinary pet-care questions, so they fall through.

    Write intentsaction_intent.py

    Book, reschedule, cancel, remind, register. The model extracts slots as JSON, and every pet, owner, vet and date is then resolved by SQL. The handler proposes an action; nothing is written until a person confirms it.

    Clinical toolsclinical_tools.py · vet & admin

    History summaries, consultation notes, aftercare and pre-visit briefings. Every relevant row is fetched by SQL, because a "full history" built from a top-5 sample is a partial history.

    Pet health riskpet_health_intent.py · vet & admin

    Recurrence, cancer and pandemic risk computed live by the risk engine above, never from retrieved text.

    Chartschart_intent.py · staff

    Claims a question only when it contains a trigger word (chart, graph, plot, visualise), so "what's our revenue?" stays a sentence. It runs just before the exact-query handler because the two share nouns.

    Exact queriesstructured_query.py

    Counts, lists, clinic hours and an owner's own balance, all answered by deterministic SQL. The language model never totals anything.

    Retrievalretrieval.py · pgvector

    The question is embedded and matched against the five nearest chunks by cosine distance, with role and owner filters applied inside the SQL. The local model then writes an answer grounded in those chunks.

    What gets embedded

    Medical records, disease cases, lab-report metadata, vaccinations, public FAQs and internal staff FAQs. Each record becomes one chunk, so one citation points to one record. Chunks are embedded locally with nomic-embed-text (768 dimensions), and the demo database holds 702 of them.

    Chunk format · medical record (example values)

    Medical record for Bella (Dog Labrador Retriever). Visit date: 2026-08-14 Chief complaint: Itching and hair loss on flank Diagnosis: Flea allergy dermatitis Treatment: Topical therapy, flea control plan Follow-up required, date: 2026-08-28 Attending veterinarian: Dr. … — stored with pet_id, customer_id, source_type

    Kept in sync, not rebuilt. Saving a record re-embeds just that record. Deleting one deletes its chunk; there's no foreign key to cascade, so a missed hook would leave the assistant citing deleted data. Renaming a pet re-embeds all of its chunks, because the name is part of the text.

    Citations are data, not prose. The retrieved chunks come back with the answer and appear as source chips. The model is told not to write "(Source 1)" inline. Guest search has a relevance cut-off, so a question no FAQ matches doesn't show five loosely related FAQs as if they were its sources.

    Scope is enforced in the query

    The role and owner ID come from the verified login. The client never sends them, so it has nothing to tamper with. The filters below are part of the retrieval SQL itself.

    CallerChunks the search can see
    GuestPublic FAQs only: no pet, no owner, no staff FAQs
    Pet ownerChunks carrying their own customer ID, plus public FAQs
    ReceptionistClinic-wide, excluding medical records, disease cases and lab reports
    Vet, adminClinic-wide, including internal staff FAQs

    Sized for one clinic machine

    Everything runs on a 16 GB machine through Ollama. Text (qwen3:8b) and vision (qwen3.5:9b) are deliberately separate models. Both can't stay in memory at once, so Ollama swaps in whichever one a request needs, and the first request after a switch waits for the swap. Every call shares one 8,192-token context window: a pet-owner question alone measures about 3,600 tokens before the answer starts.

    How it works

    One backend, one set of rules

    The web and iOS apps never touch the database or the AI directly. Every request passes through the backend, which establishes who is asking before any question is read.

    1 · Identify

    The backend verifies the login and attaches role and owner ID itself. The app can't claim more access than it has.

    2 · Route

    The question goes to the handler that can answer it: an action, a clinical tool, a live risk model, an exact SQL query, or search.

    3 · Answer

    Only then is the local model used — to phrase the answer, cite sources, or draft text for a person to review.

    Data model

    One database, records and vectors side by side

    The core schema has 17 PostgreSQL tables. Migrations add the pgvector store and a few AI tables. The diagram shows the tables that hold the clinic's records.

    customersowners · portal login petsspecies, breed, birth date medical_recordsdiagnosis, treatment, Rx vaccinationsvaccine, next due date billinginvoices in rupees appointmentsslot, vet, status disease_casescategory, severity, region lab_reportsfile + findings paymentsamount, method billing_itemsinvoice line items rag_chunkstext + vector(768) usersstaff and their roles inventorystock, reorder level inventory_transactionsstock in and out

    Select a table

    Hover over or tab to a table to see what it links to.

    Staff accounts (users) are referenced from nearly every table: as the vet on appointments and records, and in the created-by and updated-by audit fields. Those lines are left out to keep the diagram readable.

    Rules in code

    Booking rules, live in your browser

    Self-service booking follows constants defined in a single file, which both the booking endpoint and the availability endpoint read, so they can't drift apart. The slot picker below applies the same rules against your clock.

    • Open Monday to Saturday
    • 09:00–18:30, 30-minute slots
    • Up to 3 bookings share a slot
    • At least 48 hours' notice to book, move or cancel
    Choose a slot to see what the server would say.

    Slot occupancy is simulated. The day, hours and lead-time checks mirror appointmentRules.js.

    Evaluation

    How it's checked

    The code's pure logic is covered by unit tests. The parts that need a live database and a local model are covered by written manual procedures, which are run before every demo.

    SuiteCoversTests
    Booking rulesOpen days, closing-time fit, slot spacing, 48-hour lead time13
    Auth utilitiesHashing, token tampering, a customer token can never pass staff auth10
    Role checksEvery role against every guard8
    Chat UISource-citation labels and the FAQ-grounding check10
    Model clientCurrency normalisation and stray-token stripping9
    Answer clean-upRemoving imperial-unit asides without touching metric text6
    TotalNode test runner, Vitest, pytest56
    • Role-boundary walkthrough. A fixed question set for each of the five access modes, plus refusal tests that pass only when the assistant declines. Examples: a guest asking about medication, a receptionist asking for a diagnosis, a receptionist asking for a clinical chart.
    • Wrong-pet check. Every cited source must belong to the pet in the question. A fluent answer with no source counts as a failure.
    • Chart control pairs. The same question with and without "chart" confirms the trigger word neither over-fires nor under-fires.
    • Client and server guard parity. A route hidden in the UI must also be refused by the API, because the server is the enforcement point.
    Challenges & lessons

    What broke, and what it taught

    A wrong count looks exactly like a right one

    Plain RAG answered "how many pets are named Max?" from five retrieved chunks, with a confident, well-formatted, wrong number. An invented drug name looks odd; a wrong count doesn't.

    Fix: aggregate questions go to SQL. The model is also told to decline any count it would have to compute from a sample.

    "Max" is four different dogs

    Unscoped search on a common name returned several pets' records blended into one story.

    Fix: names are resolved by database lookup. When more than one pet matches, the assistant asks which one, with each option labelled by its owner. With no server session, the half-finished request travels back and forth through the client.

    The model truncated itself silently

    Ollama's default 4,096-token window was smaller than several prompts. It dropped the front of the context (the system prompt first) and still reported a clean finish, so answers just stopped mid-thought.

    Fix: one fixed 8,192-token window for every call. A value of 16,384 crashed the machine by running out of memory. Overruns are now detected from token counts and logged.

    Two models, 16 GB

    A single model for both text and photos, or keeping two warm at once, doesn't fit the clinic's hardware.

    Fix: separate text and vision models that Ollama swaps on demand. The only cost is a one-off delay when switching between them.

    Instructions a small model won't follow

    However the prompt was worded, the local model kept adding "(65 lbs)" after metric weights.

    Fix: when a small model reliably breaks a rule, enforce the rule in code. A tested regular expression now strips those asides.

    Deleted records kept talking

    Vector chunks have no foreign key to the records they came from, so deleting a medical record left its chunk in search results.

    Fix: every create, update and delete path now calls the matching re-embed or delete hook. Renaming a pet re-embeds all of its chunks.

    The journey

    From clinic system to AI decision support

    1. Project starts

      Repository created for Pro Pet Animal Hospital's management system.

    2. Core build

      React client, Express API and the PostgreSQL schema laid down.

    3. Clinic system demonstrated

      Presented on a demo dataset in mid-February. The Flask ML service and first disease model followed within days.

    4. Forecasting and risk

      Sales and inventory models trained. The pet health risk engine was added.

    5. AI Launchpad begins

      Requirements written, the iOS app started and the RAG assistant built. It was completed for receptionists, vets and admins by the end of the month.

    6. Hardening and new tools

      Unit tests, charts in chat, the AI daily briefing, and AI Visual Care for pet owners.

    7. Public case study

      Briefing caching, and this site.

    Built with

    Tech stack

    Frontend

    React 19
    Vite
    React Router
    Recharts

    Backend

    Node.js
    Express 5
    PostgreSQL
    JWT auth

    ML service

    Python · Flask
    scikit-learn
    Prophet
    Pandas

    AI assistant

    Ollama (local)
    qwen3:8b · text
    qwen3.5:9b · vision
    pgvector, 768-dim

    Mobile

    Swift
    SwiftUI
    iOS native

    Roadmap

    Where it goes next, and where it never will

    Deferred work is a matter of timing. The boundaries on the right are permanent and don't depend on any release.

    Next

    Closes gaps the assistant already runs into.

    • Lab report text. Extract text from PDFs and scans so the assistant can answer from values, not just metadata.
    • Push notifications. Appointment and vaccination reminders on iOS.
    • Typo-tolerant names. Fuzzy matching for pets and owners.

    Later

    Larger steps beyond the first release.

    • Android app. The backend already serves any client.
    • Multiple clinics. Today's design assumes a single practice.
    • Online payments. Payments are recorded today, not processed.
    • Voice input and longer conversation memory.

    Never

    Boundaries by design.

    • Diagnose. Every response is decision support for a veterinarian.
    • Act on its own. No write, saved note or email without a person's approval.
    • Free-form text-to-SQL. Every query is written in advance, and the model only fills slots.
    • Send data to a cloud model. Inference stays on the clinic's machine.

    See it running

    The live demo runs VetCare One for Pro Pet Animal Hospital with one-click logins for every role. Fictional data, reset nightly.