Skip to content

AI Features

AI booking agent, voice, style advisor, AI accountant, and the two AI gateways (provider failover).

8 min read

Overview

Kagami has several AI features. They share one provider layer, web/src/lib/ai/llm.ts, which talks to any OpenAI-compatible /chat/completions endpoint and fails over down an ordered list of providers. With ANTHROPIC_API_KEY set, Claude Haiku 5.5 direct from Anthropic is the primary model for the chat agent and the phone agent (SALO-3079). Backups: OpenRouter (DeepSeek) for chat, Gemini for phone calls. Without the key the chain is the old OpenRouter-first one. Anthropic is also the only provider that can read images.

Kagami artificial intelligence suite featuring automated front-desk voice receptionist and smart scheduling

There are two entry points on top of that layer:

Entry point Code Used by
Agent gateway (tool-calling loop) web/src/lib/ai/gateway.ts (runAgentTurn) WhatsApp/Instagram/Messenger/web-widget booking agent, phone agent (Plivo and Dograh chat-completions)
Capability gateway (one-shot text calls) web/src/lib/ai-gateway/index.ts (callAI) AI accountant, Ask Your Data, forecasting summaries, campaign copy, review/social replies, style analysis, playbook editor

Provider chain and models

loadProviders() in llm.ts builds the list from environment variables. A provider is skipped if its key is not set. Default order for chat (WhatsApp, Instagram, Messenger, web widget):

  1. Anthropic (ANTHROPIC_API_KEY), through its OpenAI-compatible endpoint https://api.anthropic.com/v1. Model ANTHROPIC_MODEL, default claude-haiku-5-5 ($0.10 in / $0.50 out per 1M tokens). The brand model setting is not used here unless AI_HONOR_BRAND_MODEL=1 (see below).
  2. OpenRouter (OPENROUTER_API_KEY). Model OPENROUTER_MODEL, default deepseek/deepseek-v4-flash-0731, sent with reasoning: { enabled: false }. Base URL OPENROUTER_BASE_URL (default https://openrouter.ai/api/v1).
  3. OpenRouter to Groq (only when OPENROUTER_GROQ_BYOK=1). Model OPENROUTER_GROQ_MODEL, default openai/gpt-oss-20b.
  4. Groq direct (GROQ_API_KEY). Model GROQ_MODEL, default openai/gpt-oss-20b.

AI_ANTHROPIC_PRIMARY=0 is the kill switch: it restores the old order (OpenRouter, OpenRouter to Groq, Groq, Anthropic last).

Phone calls (channel === "phone", applyVoiceModel()): Anthropic with ANTHROPIC_VOICE_MODEL (default claude-haiku-5-5), then Gemini (GEMINI_API_KEY, the same variable the voice gateway uses for speech-to-text; GEMINI_VOICE_MODEL, default gemini-2.5-flash, via https://generativelanguage.googleapis.com/v1beta/openai; cost defaults $0.30 / $2.50 per 1M, GEMINI_COST_IN_PER_1M / GEMINI_COST_OUT_PER_1M), then the chat backups. The OpenRouter provider still gets OPENROUTER_VOICE_MODEL (default anthropic/claude-haiku-5.5) and its reasoning field. With AI_ANTHROPIC_PRIMARY=0 the phone order is the rest, Gemini, Anthropic.

Anthropic compatibility endpoint notes. Only fields that endpoint accepts are sent to Anthropic and Gemini (OpenRouter's reasoning and provider stay on OpenRouter). temperature is not sent to Anthropic at all: Claude 4.7+ models return 400 for any non-default value. Claude 5 models think by default, so Haiku 5.x requests carry thinking: {"type": "disabled"} (Anthropic accepts that for Haiku 5.5 at its default effort); set ANTHROPIC_DISABLE_THINKING=0 to stop sending it if the endpoint ever rejects it. Prompt caching is not available through this endpoint.

Daily spend guard (anthropic-spend-guard.ts). Set AI_ANTHROPIC_DAILY_CAP_USD (unset or 0 = no cap). Before each agent turn (and each callAI text call) the gateway re-checks, at most once a minute, today's (IST day) Anthropic spend in ai_usage_log (rows whose model is anthropic:* or claude-*, summed from cost_usd_micro). At or over the cap, loadProviders() leaves Anthropic out, so chat goes to OpenRouter and phone calls to Gemini, and a warning plus a ai.anthropic_daily_cap error event is raised once. It switches back on at the next IST midnight (or when spend drops under the cap). A failed lookup keeps the previous state and is reported as ai.anthropic_cap_check. The cap counts what Kagami logs; usage from other tools on the same API key is not seen.

Failover (chatWithFailover): any failure (network, 25 s timeout, HTTP error, malformed body) moves to the next provider. If all fail, the thrown error lists every provider's failure. With no provider configured it throws No LLM provider configured: set OPENROUTER_API_KEY and/or GROQ_API_KEY.

Cost per 1M tokens for logging comes from OPENROUTER_COST_IN_PER_1M / OPENROUTER_COST_OUT_PER_1M, the GROQ_COST_* and GEMINI_COST_* variables (defaults in llm.ts); Anthropic costs are fixed per model tier in llm.ts (Haiku 5.x $0.10/$0.50, older Haiku $0.80/$4, Sonnet $3/$15, Opus $15/$75).

Per-brand model setting

Settings, AI Agent has a model field (ai_agent_settings.model, DB default claude-sonnet-4-6). It is ignored unless AI_HONOR_BRAND_MODEL=1, because the DB default would otherwise move every brand off the cheap primary. When honored, a claude-* or anthropic/* model goes to Anthropic first with that model (or to OpenRouter as anthropic/... when no Anthropic key is set), a groq/* or gpt-oss/llama-3 model goes to Groq first, and anything else replaces the OpenRouter model and keeps OpenRouter first. Without the flag, Anthropic uses ANTHROPIC_MODEL, never the brand model.

Capability gateway (callAI)

  • Each capability has a default Claude model name in CAPABILITY_MODEL (ai-gateway/index.ts): Haiku 4.5 for book, reschedule, reply-review, reconcile, summarize, query-data, retail-recommend; Sonnet 4.6 for draft-campaign; Opus 4.8 for style-analysis and consult-assist.
  • When ANTHROPIC_API_KEY is not set (or the Anthropic daily cap has tripped), text calls ignore those names and run through the OpenRouter/Groq failover chain above (production's setup before SALO-3079). The logged model is <provider>:<model>.
  • With ANTHROPIC_API_KEY set, text calls go straight to Anthropic with the capability's model above (Sonnet 4.6 for campaigns, Opus 4.8 for style analysis and consult), not through the chain; that spends the credits at those models' rates.
  • Calls that contain an image block (style analysis, in-chair consult) cannot use that path. They call Anthropic directly and throw ANTHROPIC_API_KEY is not configured in environment if the key is missing.
  • Budget: checkBudget(orgId) reads ai_token_budgets (monthly_limit, hard_stop) against the month's ai_usage_log. With hard_stop and the limit reached, the call is refused with Monthly AI token budget exhausted .... No budget row means unlimited.
  • Every call writes a row to ai_usage_log (tokens, micro-USD cost, success, error code).

AI Booking Agent (WhatsApp and other chat channels)

The booking agent runs inside the web app (web/src/lib/ai/), not as a separate service. WhatsApp inbound goes through app/api/webhooks/whatsapp, whatsapp-turn-queue.ts and whatsapp-agent-runner.ts into runAgentTurn. The agent also serves Instagram, Messenger, the web chat widget and phone (channel in AgentContext). apps/ai-services/ is dormant code with no deploy target.

Conversation flow

  1. The client sends a message. Opt-outs ("STOP"), inbound spam and per-sender rate limits apply (80 messages per sender per day and 1500 per brand per day, then the message is dropped or a notice is sent).
  2. The model works through tools: list_services, check_availability, get_staff_for_service, get_salon_info, switch_store, get_promotional_offers, get_service_combos, get_upsell_recommendations, present_choices (WhatsApp tappable lists/buttons), get_client_appointments, check_wallet_balance, and handoff_to_human.
  3. Writes (create_booking, cancel_appointment, reschedule_appointment, add_services_to_appointment) go through a propose-then-confirm step (propose_booking, propose_cancel, propose_reschedule). The write runs only after an explicit yes, and the closing confirmation text is written by code, not by the model.
  4. Replies are checked by code before sending (grounded prices and slot times, discount cap, no other client's data, no leaked tool or system text). A failed check retries or hands off.

Reply jury (optional)

With AI_REPLY_JURY=on, up to three independent models score the drafted reply. Below 0.8 confidence, or if fewer than two judges answer, the reply is held for staff instead of being sent. Off by default.

Human handoff

The agent calls handoff_to_human for a request for a person, a complaint, a refund request, a treatment reaction or injury, anger or legal threats, bridal/on-site enquiries, retail product enquiries, and anything it cannot help with. The conversation is flagged in the Inbox for the front desk, and the AI stays out of that chat for 12 hours (HANDOFF_PAUSE_MS) or until staff press Resume bot. A staff reply typed in the Inbox pauses the AI and cold follow-ups for 2 hours.

Guardrails

  • Slots come from the scheduling engine (check_availability), so the agent cannot book a taken or out-of-hours slot.
  • Discounts: price objection only, never the opening line, capped at 20% (AI_DISCOUNT_MAX_PCT).
  • Org token budget via checkBudget before each turn.
  • All actions are logged to ai_action_logs (tokens, cost, conversation).

Follow-ups and nudges

  • Cold-chat follow-ups (cron ai-chat-recovery, every 5 minutes, cart-recovery.ts): up to three free-text nudges after the agent's last reply, at about 5 minutes, 30 minutes and 23.5 hours. They only go out 08:00 to 21:00 salon time, only inside Meta's 24 h window, and stop if the client declines, says they will get back, is in the salon, or books.
  • Booking and pre-arrival upsell nudge (ai-pre-arrival-nudge, every 15 minutes): offer after booking, and again 20 to 28 hours before the visit.
  • See AI Revenue Agents PRD for the revenue agents (upsell, whitespace flash offers, waitlist fill, NPS and referral).

AI Voice

There are three separate voice features:

Feature Where What it does
In-app Voice Assistant Dashboard, AI Voice Assistant (/dashboard/voice-assistant, components/voice-assistant/, lib/voice/assistant-actions.ts) Staff speak or type a front-desk command. One LLM call with three tools (create_appointment, create_bill, log_expense) turns it into a parsed action. The user confirms before anything is written. Uses chatWithFailover directly. Needs microphone permission on native apps.

Call history is under Dashboard, Voice Calls. This repo has no call-recording storage; recordings, if any, live with the voice provider.

AI Style Advisor

lib/style-analysis/index.ts. A client or stylist photo plus optional context goes to callAI with the style-analysis capability (face shape, undertone, hair texture, skin condition and ranked service recommendations as JSON) or consult-assist (in-chair service sequence and product pairings). Because the input is an image, it requires ANTHROPIC_API_KEY (see above). Without it the call fails with an explicit configuration error.

AI Accountant

lib/accounting/ai-accountant.ts. It does not read the database directly in the prompt. Code builds a structured snapshot and the model categorises expenses (with confidence and reasoning) and answers questions about it, using the reconcile and query-data capabilities. Answers are analysis assistance, not certified accounting advice.

Marketing copy, review replies, forecasting

  • Campaign builder (lib/marketing/campaigns.ts): draft-campaign, Sonnet by default when Anthropic is configured. A human reviews before sending.
  • Review and social replies (lib/reputation/reviews.ts, social.ts): reply-review. Drafts only; a human approves before posting.
  • Forecast summaries (lib/forecasting): summarize, narrative over statistical output.
  • Ask Your Data (lib/analytics/ask-your-data.ts): query-data.

Audit and usage logs

  • ai_usage_log: capability-gateway calls (org, brand, capability, model, tokens, cost, success, error code).
  • ai_action_logs and ai_messages: agent turns and the full tool-call transcript per conversation.
  • The Inbox shows AI conversations; Settings, AI Quality shows weekly metrics from the ai_quality_weekly view (migration 0238).

Evaluation

The eval harness lives in web/src/lib/ai/eval/ (see its README.md). It is a repo test tool, not a production monitor.

  • npm run ai:eval (from web/) replays a versioned golden set of about 56 WhatsApp conversations through the real runAgentTurn with Supabase and tools mocked. Offline mode uses scripted model output and checks the gateway guards; it is also part of npm test.
  • AI_EVAL_LIVE=1 npm run ai:eval runs against the real providers and writes web/eval-reports/latest.{json,md} (gitignored).
  • npm run ai:bakeoff compares candidate OpenRouter models on the same set.
  • An optional LLM judge runs only when AI_EVAL_JUDGE_API_KEY and AI_EVAL_JUDGE_MODEL are set.

There is no nightly golden-set job, no thumbs up/down collection and no A/B prompt rollout in this codebase.