Case study · 2026
Kiku: Safe AI Play Companion for Children (Gemma 4 · Flutter · FastAPI)
Conversational AI · Multimodal LLM · AI safety guard rails · Flutter + FastAPI
Personal AI product · Built solo, Aug – Oct 2026 · Server and model live on Railway; app complete, App Store setup and the final safety-policy review before launch
Kiku is an AI friend for young children that sees, listens and talks back. A child holds one big button, says what they found, and Kiku answers out loud. Parents get a separate grown-up area with time limits, transcripts, progress and full control of what Kiku remembers. Safety and trust are the product.

- Solo builder · AI engineer · Flutter app, backend, model hosting
- 2026
- Conversational AI
- 13 technologies
- Gemma 4 (Ollama)
- Gemini on Vertex AI
- Multimodal LLM
- Structured output
- AI guard rails
- Flutter
- GetX
- FastAPI
- PostgreSQL
- SSE streaming
- Firebase Auth + App Check
- RevenueCat
- Railway
4
Games: I Spy, counting, story, drawing
318
Automated tests (193 app, 115 server, 6 live Gemma, 4 contract)
~4–5 s
Per turn on Gemma 4 on CPU (Railway)
0
Photos stored, anywhere (no image column)
~19K
Lines of code (15K Dart, 3.4K Python)
3
Model providers behind one interface
App screens
Real screens from the iOS simulator. The child surface is warm and oversized; the parent surface is cool and dense. Demo data from the app's mock backend. · tap to enlarge
The problem
General chatbots are not built for a four-year-old. They can say anything, they keep photos and transcripts, they let the client decide limits, and they have no idea who the child is from one day to the next. Putting an LLM in front of a young child raises every hard question in applied AI at once: how do you stop the model saying something it shouldn't, how do you use photos without keeping them, how do you personalise without collecting personal data, and how do you make sure a modified phone can't buy more screen time or unlock paid features.
Overview
Kiku plays four games: I Spy, counting, story and drawing. In the camera games the app takes one frame when the child lets go of the button and sends it with the transcript. A multimodal model looks at the picture, judges the answer, and replies in a fixed JSON shape: the lines to say, whether the answer was correct, the next target, a one-sentence description of the scene, new words, and anything worth remembering.
The model never decides the flow. A deterministic Play Loop on the server owns the game: it picks the mode and target, grades, updates mastery per skill, celebrates, and winds the session down. The LLM only writes the words. This is the same principle I use in my CrewAI work: let the model reason and generate, but keep control flow, state and safety in code.
Every turn passes through a safety pipeline that sits above the model interface. The child's words are checked before any model sees them; a blocked or escalated turn never reaches the model, photo included. The reply is checked sentence by sentence before anything is sent, and one bad sentence replaces the whole reply with a gentle deflection. Only then is the reply streamed back over SSE, one sentence at a time, so it still feels fast.
The model is Gemma 4, self-hosted with Ollama on a private Railway service with no public domain, so a child's words and photos never leave infrastructure I control. The provider interface also supports Gemini on Vertex AI and a deterministic fake for tests; one setting picks the model, and swapping it never touches safety code. Because Apple-silicon runners can't hold Gemma to a JSON schema, the provider learns that at runtime and falls back to prompt-level JSON with validation and one retry.
Each child has their own memory. Before every turn the server assembles what it knows about that child only (likes, level per skill, recent words, last session's highlight), re-checks each item against the current safety policy, and adds it to the prompt. New memories are kept only in categories the policy allows, never names of people, places or schools. Parents can see and delete every fact, and the delete removes the source events too, so it never comes back.
The phone is treated as untrusted. Quota, grading, entitlements and safety all live on the server. Firebase Auth is parent-only, App Check attests every call, and RevenueCat's webhook is the only thing that can unlock Premium. A model activity log records every call's latency, attempts and token counts, but never the child's words, the reply or the photo.
Architecture
System architecture
One repository, three trust zones. The Flutter app renders what the server sends and decides nothing about safety, time or grading. The FastAPI server owns every decision. The model sits below the safety pipeline. Each layer links to its code.
- Channels
- Service
- AI agents
- External API
- Data & infra
- Client UI code
Client app (the UI)
Child surface
Warm and oversized (72 dp targets): home with a time-left dial, four games, the Play screen with camera window, Kiku avatar, live caption and hold-to-talk.
Parent surface
Cool and dense (48 dp): overview, progress, memory, children, settings, transcripts, privacy and a paywall behind a grown-up check.
Device services
On-device speech-to-text and text-to-speech, camera frame held in memory only, haptics.
ApiClient + SSE
Streams Kiku's reply sentence by sentence. A child never sees an error: failures become something Kiku says.
HTTPS + SSE · Firebase ID token + App Check token - Routers code
API gateway
Size check first
Oversized requests rejected before parsing
Auth + App Check
Firebase token verified; every row scoped to the parent's uid
Quota enforcer
Per child, per local day; idle time capped at 2 minutes; 429 before any model spend
Entitlements
Free vs Premium decided from RevenueCat's webhook, never from the phone
only cleared turns continue - Safety pipeline code
AI orchestration and guard rails
Input guard
Normalise, then escalate or block against the owner's YAML policy before any model sees the words
Play Loop
Deterministic state machine: mode, target, grading, mastery, celebration, wind-down
Per-child knowledge
Likes, level, recent words, last highlight, each re-checked against the policy
Output guard
Every sentence, every stored field; all or nothing, with a gentle deflection
LLMProvider protocol (providers/base.py) - Provider code
LLMs
Gemma 4 on Ollama
Text + images, self-hosted on a private Railway service; cloud models and ollama.com refused
Gemini on Vertex AI
Alternative provider with schema-constrained JSON output
Fake provider
Deterministic replies for development and the test suite
SQLAlchemy 2 async + Alembic - Deploy code
Data and infrastructure
10 tables
children, sessions, turns, quota_usage, skill_progress, memory_facts, memory_events, safety_incidents, entitlements, model_calls
No image column
Camera games keep a one-line scene description, never the photo
Railway project
kiku-api (Docker), Postgres, and a private Ollama service with a model volume
Architecture diagrams
Six diagrams, from the big picture to the details: the system and its trust zones, one turn of play end to end, the guard rails around the LLM, per-child memory, the Flutter app's layers, and deployment with the Gemma provider's fallback. They are drawn from the code and the repository's documentation. Tap any diagram to zoom.
System architecture
Four columns: the phone, identity and purchases, the trusted server, and models and data. The key decision is the order inside the server: gate, then quota, then the safety pipeline, then the Play Loop, and only then the model.
- The app holds no safety logic, no quota maths and no grading. It renders what the server sends
- The safety pipeline sits above the provider interface, so changing models never touches safety code
- Gemma 4 runs on a private service I control; Gemini and a fake provider plug into the same protocol
- RevenueCat's webhook is the only writer of entitlements, so Premium can't be faked from the phone
One turn of play, end to end
A full turn from the button press to Kiku speaking. The app shows "thinking" before any network call. Nothing is streamed until the whole reply has passed the output guard; speed comes from streaming sentence by sentence afterwards.
- Steps 4–6: the cheapest checks run first, and quota is enforced before any model spend
- Step 7: a blocked turn never reaches the model, and the incident records which rule fired, never the words
- Steps 8–9: the model gets the policy's instructions, this child's knowledge, the last 12 lines and the photo, and must answer in a fixed JSON shape
- Steps 10–11: all-or-nothing output guard, then one SSE frame per sentence with the quota on the last
Guard rails around the LLM
This is the agentic heart of Kiku. The model is free to generate, but deterministic code decides what goes in, what comes out, what is remembered, and what happens next.
- Escalation outranks a block: a child who says something a grown-up should know about is recorded for review and steered back to the game
- Output is checked for length, contact details and blocked terms; one failure deflects the whole reply
- Even fields a parent reads later (scene description, highlight) and memory candidates pass the guard before they are stored
- The Play Loop, not the model, decides grading, mastery and when to wind down
Personal memory, per child
Long-term memory without a vector database and without collecting personal data. Memory is small, typed by category, scoped to one child, and treated as untrusted on the way out as well as on the way in.
- Four kinds of knowledge feed the prompt: likes, level per skill, words met recently, and last time's highlight
- Only policy-approved categories are kept, and never names of people, places or schools
- Forgetting goes to the server first and deletes the source events, so a fact can't be re-learned from old data
- The parent's phone keeps an offline copy scoped to the signed-in parent
The Flutter app: Clean Architecture with GetX
Dependencies point inward. The domain layer is pure Dart and its use cases return Result<T> instead of throwing, so a child never sees an error screen.
- One composition root builds every repository, so the app runs fully on an in-memory mock backend with no server
- Thin GetX controllers; PlayController only sequences the microphone, camera and animation around server decisions
- Two surfaces share one design-token set: warm and oversized for the child, cool and dense for the parent
Deployment and the Gemma provider
Three services on Railway's private network. The model has no public domain. On the right, how the provider keeps structured output reliable on runners that can't enforce a schema.
- Gemma 4 (gemma4:e2b-it-qat) on CPU, one thread per core: about 4–5 seconds a turn
- Schema first; on a 501 the provider switches to prompt-level JSON for good; one retry, then a gentle 503
- Every call leaves one model_calls row with timings and token counts, never content
Tools & tech
AI & models
- Gemma 4 (gemma4:e4b / e2b-it-qat)
- Default multimodal model, text and images, self-hosted
- Ollama
- Model runtime, on a private Railway service and on an M2 Mac for development
- Gemini on Vertex AI (google-genai)
- Alternative provider with schema-constrained output
- Pydantic
- The ProviderReply schema and every API boundary
App
- Flutter + GetX
- iOS and Android app with Clean Architecture
- speech_to_text · flutter_tts · camera
- Voice in, voice out, and in-memory camera frames
- Lottie (generated)
- Onboarding animations generated by a Python script from theme colours
- Firebase Auth + App Check · RevenueCat
- Parent sign-in, device attestation and subscriptions
Backend & infrastructure
- FastAPI + SSE
- Turn endpoint streaming one frame per sentence
- SQLAlchemy 2 (async) + Alembic + PostgreSQL
- 10 tables, migrations on deploy
- Railway
- API (Docker), Postgres, and the private Ollama service
- pytest · ruff · flutter test
- 318 tests across app, server, live model and contract
Modules & code
Flutter app
Child and parent surfaces, GetX controllers, Clean Architecture, HTTP + SSE client, Firebase and RevenueCat sources, and a full in-memory mock backend.
lahirumanulanka/kiku-ai-bot/tree/main/libScreens
Splash, onboarding, child home, play, parent dashboard, progress, memory, children, settings, sessions, transcript, privacy, about, paywall.
lahirumanulanka/kiku-ai-bot/tree/main/lib/presentation/pagesFastAPI server
Routers for children, sessions, turns and entitlements; quota enforcer; activity log; Alembic migrations.
lahirumanulanka/kiku-ai-bot/tree/main/backendSafety pipeline
Input and output guards, text hygiene, contact-detail detection, and the owner's YAML policy loader.
lahirumanulanka/kiku-ai-bot/tree/main/backend/app/safetyPlay Loop
The deterministic game state machine, the four game modes, and per-child knowledge for personalisation.
lahirumanulanka/kiku-ai-bot/tree/main/backend/app/playModel providers
LLMProvider protocol with Gemma 4 (Ollama), Gemini (Vertex AI) and a fake provider; structured ProviderReply schema.
lahirumanulanka/kiku-ai-bot/tree/main/backend/app/providersGemma service
The private Ollama service for Railway, with the model pulled once onto a volume.
lahirumanulanka/kiku-ai-bot/tree/main/deploy/ollamaTests
Widget, controller and repository tests; safety, quota, auth, entitlement and provider tests; live Gemma tests; app ↔ server contract tests.
lahirumanulanka/kiku-ai-bot/tree/main/backend/tests
Key features
- Hold-to-talk voice play with on-device speech recognition and spoken replies, streamed sentence by sentence
- Multimodal games: Kiku looks at a camera frame to judge I Spy, counting and drawing answers
- Personal memory per child that changes how Kiku plays, with every fact visible and deletable by the parent
- Server-side daily time limit per child, counted from activity, with a gentle wind-down that never cuts a child off mid-game
- Parent dashboard: minutes played, sessions, new words, streak, weekly chart, skill progress, highlights and full transcripts
- Up to four children per family, each with their own profile, memory, mastery, quota and Kiku colour
- Free (I Spy, counting, one child) and Premium (all games, up to four children, memory in play) via RevenueCat, $4.99/month or $39.99/year
- Paywall behind a grown-up check, with everything App Review asks for: prices, trial terms, renewal, restore and manage
AI engineering decisions
- Structured output as a contract: the model must return a ProviderReply (lines, outcome, next target, scene description, new words, memory candidates, highlight), validated with pydantic, so the Play Loop never parses free text
- Model-agnostic by design: a small LLMProvider protocol with Gemma, Gemini and a fake. The fake makes the whole pipeline testable without a GPU or an API key
- Self-hosted open model for privacy: Gemma 4 on Ollama keeps children's words and photos inside my own network, and Gemma's terms carry no under-18 restriction
- Prompt assembly from policy + game rules + per-child knowledge + a 12-line text window; photos are passed once and dropped
- Runtime capability detection: the provider tries schema-constrained decoding, learns when a runner can't support it, and switches to prompt-level JSON with validation and one retry
- Observability without surveillance: a model activity log (p50/p95 latency, retries, photo yes/no, token counts, personalisation count) that never stores content
Agentic patterns I apply with CrewAI too
- Kiku runs one model per turn rather than a crew, but it is built on the same principles as my six-agent CrewAI pipeline in BrokeMe: narrow responsibilities, typed outputs, and deterministic orchestration around the LLM
- The Play Loop plays the role of a CrewAI orchestrator: it fixes the order of steps, saves state after each one, and decides what happens next; the model never picks the flow
- The input and output guards are the equivalent of a validation and moderation crew, implemented as fast deterministic code so they can't be talked out of a rule
- Structured ProviderReply output is the same idea as a CrewAI Task with an output_pydantic model: every stage hands the next one a validated object, not prose
- Memory candidates work like a crew's long-term memory with a policy gate in front of it: the model proposes, code decides what is kept
- Tested the same way: the LLM is stubbed with a deterministic fake in CI, and a separate live suite runs the real model through the real pipeline
Security & privacy
- No photo is ever stored: one frame is captured, sent, and dropped; the plugin's temp file is deleted before the bytes are returned, and the database has no image column
- Safety logic never runs on the phone; the server refuses to start Gemma without a safety policy, and refuses Ollama cloud models as a host
- Firebase Auth is parent-only; no password is stored or logged, and an auth failure never reveals whether an address is registered
- App Check on every backend call: App Attest on iOS, Play Integrity on Android
- Quota is never computed on the device, so changing the phone's clock can't buy more time
- Safety incidents record which rule fired, never the content and never an image
- No face recognition anywhere, on either side; no third-party analytics (Apple Kids Category)
Status & roadmap
- Live: the API, Postgres and the private Gemma service are running on Railway, verified end to end against the real model
- Before launch: final line-by-line review of the safety policy, and App Store Connect / RevenueCat product setup
- Next: on-device speech recognition everywhere, so voice never leaves the phone
- Next: Sinhala support. Copy already goes through translation keys, so a language can be added without touching a screen