Case study 01 of 07 · Voice AI · Safety · Payments
AI Hypnotherapist
A four-language, voice-first AI service that takes a client from safety screening to a personalised audio session, with a human practitioner in the loop.
In 20 seconds
- What it is
- The AI service of the Hypnotreatment practice in London. Clients pass free safety screening, pay a small fee for a spoken consultation with an AI consultant, get a free 5-minute preview, and can buy the full session as an MP3.
- My part
- Product owner and director. I defined the product, the safety and clinical rules, the prices and the sound design, tested on PC, phone and the Android app, and run the accounts. Claude Code wrote the code.
- Built with
- Claude Code (VS Code extension), Git and GitHub, pytest with a fake AI gateway
- AI in the product
- Claude Opus 5.5 for the consultation, safety classifier, intake and script writing. Open speech models run on my own server.
- Status
- Live in production. First commit 30 Sep 2026. Waiting room and server resize shipped 11 Nov 2026.
Straight answer: A real consultation needs a safety screening and a payment, so there is no free demo. Claude Code wrote the code under my direction. I own the product, the safety rules and the testing.
- 307 automated tests passing (4 skipped) verified
- 4 languages end to end verified
- ~60 HTTP endpoints verified
- 3 consultations at once, set from measured capacity verified
Overview
A client picks a language, answers free safety screening questions and pays a small fee. They then have a spoken consultation of about 20 minutes with an AI consultant: an animated avatar that speaks in the practice’s own recorded voice. The consultation becomes a structured intake and a free 5-minute preview of a personal hypnotherapy session. If they like it, they can buy the full session as an MP3, with recorded voice, time-stretched pacing, hall reverb and background music. Or they can ask for the practice’s qualified human hypnotherapist instead.
The problem. A practitioner’s time is limited. This lets people start with an affordable AI consultation and a personalised audio session at any hour, while a qualified professional stays in the loop through clinician review, referral to the hypnotherapist or a doctor, and strict safety stops.
Who it is for. Adults (18+) looking for help with smoking, weight, anxiety and stress, confidence, sleep, pain, phobias or habit control. The second user is the practice owner, who runs it from an admin dashboard.
What makes it different
- Safety is layered, not just a prompt. Free screening before payment, a keyword net plus an independent AI classifier on every client message, fail-safe behaviour when the classifier is down, and unsuitable knowledge-base sections excluded by structure.
- The voice is a real person’s recording. It is cloned and spoken locally on the server by an open model, with local speech-to-text. There are no cloud voice fees, and client audio is transcribed in memory and not stored.
- Session writing is grounded. It draws on a curated clinical library (BM25 retrieval with an ethics filter), the clinician’s own style notes and a review-and-learning loop.
- Four languages, from the screens to the helplines, emails, payment page, speech recognition and voice.
Screens
How it works
One client's journey
- Service
- External service
- AI model
- Human step
Read this diagram as a list
The boxes
- Free safety screening: unsafe or under-18 clients stopped before payment
- Pay for consultation: Stripe Checkout
- Spoken consultation: about 20 min, live safety check
- Intake extraction: Claude, structured output
- Free 5-minute preview: opening script and audio
- Buy the full session: Stripe, checked by webhook
- Script writing: Claude and the BM25 library
- Validators: headings, word counts, flagged phrases
- Clinician review: optional setting
- Session audio (MP3): voice, pacing, reverb, music
The connections
- Free safety screening → Pay for consultation
- Pay for consultation → Spoken consultation
- Spoken consultation → Intake extraction
- Intake extraction → Free 5-minute preview
- Free 5-minute preview → Buy the full session
- Buy the full session → Script writing
- Script writing → Validators
- Validators → Clinician review
- Clinician review → Session audio (MP3)
One turn of the consultation
- Client
- AI model
- Service
Read this diagram as a list
The boxes
- Browser: microphone, avatar, captions
- Speech to text: faster-whisper, in memory
- Text to speech: Pocket TTS, clinician's voice
- FastAPI: decides: continue, clarify, confirm, stop or fail safe
- Safety check: keyword net and AI classifier
- Consultant reply: Claude Opus 5.5
The connections
- Browser → Speech to text (voice)
- Speech to text → FastAPI (text)
- FastAPI ⇄ Safety check (in parallel)
- FastAPI ⇄ Consultant reply (drafts)
- FastAPI → Text to speech (approved text)
- Text to speech → Browser (voice stream)
The pipeline below runs without anyone watching, apart from the optional clinician review.
Runs without me
- Summary extraction and opening-script writing start by themselves when a consultation ends.
- Full-script generation and audio start automatically after payment.
- A one-minute loop closes consultations past their time limit and writes their summary.
- An hourly loop deletes expired audio and sends due emails.
- Abandoned paused consultations close after 24 hours, and interrupted work resumes after a restart.
- The Stripe webhook completes a payment even if the client closed the page.
Needs a person
- Optional clinician review (approve, edit or reject) before a script is released.
- A client can ask for the practice’s qualified human hypnotherapist instead.
- The practice owner sets prices, voice, music and the waiting room from the admin dashboard.
Stack
AI models and APIs
- Claude Opus 5.5consultation, safety classifier, intake, script writing
- Claude Haiku 4.5reads uploaded books, about 4x cheaper
- Anthropic SDKadaptive thinking, streaming, prompt caching
- Kyutai Pocket TTSlocal text to speech in the clinician's voice
- faster-whisperlocal speech to text
AI techniques
- Structured JSON outputPydantic-validated
- Prompt caching
- Retrieval: BM25stemming, ethics filter
- Safety classifier and guardrails
- Prompt-injection resistanceescaped client text
- Quality gates in codescript validators
- Cost and token tracking
- Local speech models
- Orchestrated LLM pipeline
Languages
- Python3.14 on the server
- JavaScriptES modules
- HTML and CSS
Backend and APIs
- FastAPI0.141.1
- Uvicorn
- Pydantic v2
- Server-sent events
Frontend
- Vanilla JavaScript (no framework)about 4,900 lines
- Web Audio and AudioWorklet
- three.jsvendored 3D head-scan avatar
Audio and media
- ffmpegmixing, hall reverb, MP3 export
- Signalsmith Stretchtime-stretching
- PyTorch (CPU)
Data and storage
- SQLite17 tables
- Files on disksession audio, voice models, outbox email
Payments and integrations
- Stripe Checkout, saved cards and signed webhooks
- SMTP emailfour languages
- Hugging Facemodel downloads
Cloud and infrastructure
- Oracle CloudAlways Free ARM, London region
- Ubuntu 24.04, systemd and nginx
Testing and tooling
- pytestfake AI, voice and payment providers
- Claude Code
- Git and GitHub
- Headless-browser checks
AI and machine learning
Models and what they do
- Claude Opus 5.5Consultation, safety classifier, intake extraction, session-script writing and lesson proposals. Configurable through one setting.
- Claude Haiku 4.5Reads books uploaded in the admin panel, because it is about four times cheaper.
Techniques actually used
- Adaptive thinking with a per-task effort setting, and streaming for long generations.
- Structured output validated against Pydantic models for every analytical step.
- Prompt caching on the system prompt and the conversation prefix.
- Seven prompts versioned by hash. Client text is escaped inside XML-style delimiters to resist prompt injection.
- The practice’s own instructions sit below the safety rules, and the safety rules always come first.
- A review-and-learning loop: the clinician’s edits are summarised into proposed ‘lessons’ that the clinician approves before they reach later prompts.
Not in this project
- Embeddings
- Vector database
- Cloud TTS or STT
- Free-roaming agents
A pipeline of specialised LLM calls with deterministic orchestration, not a free-roaming agent.
Features
- Language choice, then free safety screening. Under-18 and unsafe clients are stopped before payment, with country-specific crisis resources for GB, DE, AT, CH, FR and ES (non-UK helpline numbers are marked unverified in the content file).
- Payment for the consultation, with the price set in the dashboard, a stored cancellation-rights acknowledgement, receipts and a saved card for the later session purchase.
- A spoken consultation with live captions, an avatar that moves with the voice, silence check-ins, automatic pause, and Pause and Stop buttons (Stop is final, with a clear warning).
- Intake extraction (origin moments, triggers, suitability) and referral logic: to the hypnotherapist for pregnancy or trauma-related distress, to a doctor otherwise. Unsuitable clients are offered only the human practitioner.
- A free preview, a full-session purchase, an MP3 download, an audio retention limit, and follow-up emails only with consent and a stop link.
- A waiting room (built 11 Nov 2026) that allows at most 3 consultations at once, is checked at the Pay step so nobody pays and then waits, and never stops a paying client.
- An admin dashboard for sessions, transcripts, safety events, script review, lessons, books, voice, music, prices, the practice’s own AI instructions and the waiting room. Sign-in uses a password hash, a proof-of-work robot check, rate limiting and an alert email.
My role
What I did
- Conceived the product and the business model: a consultation fee, then an AI session, with the human hypnotherapist as an alternative. I set the prices and the cancellation wording.
- Supplied the clinical and safety expertise: the screening questions, the stop and referral rules, what the consultant must never do, how a session is structured, and the practitioner’s style (distilled from 14 of my own sessions into a style note).
- Recorded the voice the service speaks in, and made the sound decisions (speed, music, reverb, soft edges) by listening.
- Ran acceptance testing on PC, phone and the Android app, with screenshots and exact bug reports, and decided layout, the behaviour of Pause and Stop, and languages.
- Made the operating decisions: Oracle, Stripe, GitHub and Play accounts, approving deployments, shrinking the server to the free allowance, switching the waiting room on, and spending limits.
- Directed Claude Code with rules: never spend API tokens without asking, never go live without approval, verify before answering.
What Claude Code did. Essentially all the code, tests and documentation in the repository.
Engineering challenges
Safety that can’t be talked around
A prompt alone can be argued with, and a safety check that slows every reply makes a bad product.
How it was solvedHide
Two independent checks run on every message: a deterministic keyword net and an AI classifier. The consultant’s reply is generated at the same time and released only if the check passes, so safety adds no latency. If the check flags concern, the speculative reply is cancelled. If the classifier is down, the system fails safe. Tests cover the keyword net, classifier failure and the ask-once-more flow.
Natural voice on a small server
Text to speech and speech to text share four ARM cores with everything else.
How it was solvedHide
Measured on the server: voice costs about 0.49 s of work per second of speech (about 2.2 cores while speaking) and speech to text about 0.13 s per second. One priority worker thread (live conversation before background audio), a 300-phrase cache, warm-up of fixed phrases and a browser fallback voice when the first sound takes over 6 seconds keep conversations smooth.
Capacity measured, not guessed
How many clients can one small server carry?
How it was solvedHide
Using simulated clients and no AI spend: on 4 cores, 5 clients were smooth (median first sound 0.4 s) and 10 were slow (median 7.4 s, 20 of 30 replies over 6 s). After the resize to 2 cores, 2 clients had a median of 0.6 s with none over 6 s, 3 clients had 1 of 9 over 6 s, and 4 clients had 4 of 12 over 6 s. That set the waiting room at 3. One run was contaminated by the voice cache and was redone with unique sentences.
A waiting room nobody notices
Capping concurrency must never strand a paying customer.
How it was solvedHide
The check happens at the Pay step, paid clients are never stopped, and counting errors fail open. Seats count only consultation pages seen in the last minute and not paused, plus a 4-minute hold after pressing Pay, so old stuck sessions never count. A lock makes concurrent presses safe (tested with 10 threads), and queue order uses a counter, not timestamps. 17 dedicated tests plus a headless-browser walk-through: a second client queued, then proceeded by itself 7.8 s after a place freed.
Payments you can trust
A payment must count only when it really happened.
How it was solvedHide
The app checks every payment with Stripe, both on the client’s return and on the signed webhook, compares amounts and session ids, and treats double completion as idempotent. Covered by test_stripe.
Ethics enforced structurally
Prompts can be forgotten. File filters can’t.
How it was solvedHide
A library note is retrievable only if the book catalogue marks it as core craft, and unlisted files are blocked (fail closed). Sections whose headings mark them excluded, flagged or cautionary are dropped before indexing.
Interrupted work and restarts
Servers restart. Consultations shouldn’t.
How it was solvedHide
Work in flight when the server restarts is resumed, and paused or abandoned consultations are closed by a timer.
Cost control
A full consultation on a top model is not cheap.
How it was solvedHide
Cached prompts, a cheaper model for routine reading, per-call cost logging and an effort setting per task. A full consultation measured at roughly $1.1 to $1.3 on Opus 5.5 reported (token averages from earlier analysis).
Testing without spending money
Live-API tests cost real money.
How it was solvedHide
A fake AI gateway and fake voice and payment providers cover the suite, and live-API tests are skipped unless explicitly enabled. Last full run on 11 Nov 2026: 307 passed, 4 skipped.
Fitting the free infrastructure
The server was bigger than the free allowance.
How it was solvedHide
Querying the Oracle API showed the server used 4 OCPU / 24 GB against an Always Free limit of 2 OCPU / 12 GB. On my decision the data was backed up and the server shrunk, with a verified restart and about 2 minutes of downtime.
Status
Live and verified on 16 Nov 2026. ai.hypnotreatment.uk returned HTTP 200, its price endpoint returned the live price list (£5 consultation, £35 AI session), and the practice page returned HTTP 200. The waiting room has been ON with 3 places since 11 Nov 2026, checked against the server database that day. Real payments are enabled reported and the service holds real clients’ data, so this page contains none of it.
Complete
- The whole journey from screening to the delivered MP3, in four languages.
- Payments, receipts, saved cards and signed webhooks.
- Admin dashboard, script review, lessons and book upload.
- Waiting room: Off, Watch only or On.
Partial or still open
- Play Store review of Android app 1.5 reported
- Native-speaker review of the German, French and Spanish texts, and verification of non-UK helpline numbers.
- Privacy-policy and ICO fee review.
- Merging the working branch into main.
- A real-API test of the books feature with the cheaper model.
Evidence
- 307 automated tests passing (4 skipped) Last full run on 11 Nov 2026, using fake AI, voice and payment providers so the suite spends no money.verified
- 4 languages end to end English, German, French and Spanish across screens, consultant, safety questions, helplines, emails, payment page, speech recognition and voice.verified
- ~60 HTTP endpoints 36 client and public, 26 admin.verified
- 3 consultations at once, set from measured capacity Simulated clients, no AI spend. After the resize to 2 cores, 2 clients had a median first sound of 0.6 s and none over 6 s.verified
- 17 database tables SQLite, with a 30-second busy timeout and a column-migration list.verified
- 25 commits, 30 Sep to 11 Nov 2026 About 7,300 lines of application Python, 4,760 lines of tests and 4,900 lines of front end.verified
- $1.1 to $1.3 AI cost of one full consultation on Opus 5.5 From earlier token-average analysis, not a fresh measurement.reported
Code worth reading (private repository)
app/llm.pyThe single gateway: structured output, refusal fallback, typed errors and per-call cost accounting.app/service.py consultation_turnSafety check and reply running concurrently, with the reply released only on a pass.app/risk.pyLayered safety: keyword net, classifier and fail-safe behaviour.app/knowledge.pyBM25 retrieval with structural, fail-closed exclusion.app/speech.py and app/session_audio.pyLocal TTS, time-stretching, reverb and a priority worker thread.app/waiting_room.py and tests/test_waiting_room.pyThe waiting room and its 17 tests.
What I can't verify, so I don't claim
- Live-mode payment status, payment volumes, client numbers, revenue, conversion or satisfaction. No data was available.
- Whether the consultant meets any clinical or regulatory standard. The content has not been independently audited.
- Performance under real traffic. All capacity figures come from simulated clients.
- The practice website (Next.js on Vercel) and the Android app, which were not inspected.
Public links
Compiled on 16 Nov 2026 from the code, tests, the Oracle API and the live service. Items marked reported come from my handover notes.
verified checked against the code, tests, logs or the live system. reported from my own notes or hands-on use. unverified could not be checked, so it is not claimed.

