GandClaude Opus 5 198e54d38d fix(llm): take model ids from ai-kit, and try more than one (#137)
Both ids in `API_CONFIG` have been retired by their vendors:
`llama-3.1-8b-instant` at Groq and `openai/gpt-oss-20b:free` at OpenRouter. With
a valid key, this app's chatbot was answering 404.

Nothing was neglected here. The constant carried the correct instruction —
"free catalogues rot; when it does, replace it with another `:free` id" — and
that is precisely the maintenance that did not happen, because nothing tells a
constant when it has stopped being true. So the ids leave this repo. `ai-kit`
holds one list for the fleet, re-probes it against the live catalogues, and
dotfiles' daily audit asks both vendors whether those ids still exist.

One id was also not enough on its own. `generateWithBestProvider` picks ONE
provider and calls it exactly once, so a retirement had nothing between it and
a dead chatbot. Each vendor's call now walks that vendor's list: a 404 (retired)
or a 429 (busy or spent) steps to the next model instead of surfacing.

This is model-level fallback, not vendor-level — provider selection is untouched.
That is the smaller half of the protection, since a spent daily budget is
org-wide and kills every model at a vendor together. It is also the half that
covers rot, which is what actually happened here, twice.

An explicit caller override is still honoured as-is and alone. If someone names
a model, quietly answering from a different one is worse than failing.

The cost rule that lived in the deleted comment survives, and got stronger.
`free-fallback.test.ts` used to regex ONE constant; it now runs `modelCost` over
every OpenRouter id this app could send, using the same function the rest of the
fleet prices models with. OpenRouter is only reached when Groq's free tier is
spent — when nobody is watching — so a paid id there turns an outage into a bill.

The old tests deserve a note, because they passed throughout the outage: they
mocked `llama-3.1-8b-instant` and asserted it back, agreeing with production
about an id production was refusing. Worse, the OpenRouter test asserted
`anthropic/claude-sonnet-5` — a paid model on the free-tier fallback path, the
exact thing the fleet rule forbids, green the whole time. They now assert
against the chain, plus two new cases: a retired first model falls through to a
different one, and exhausting the list names the whole list.

`jest.config.js` transforms `ai-kit`, which is ESM-only. The comment there says
what does NOT belong in that list, since a transitive entry would mean a package
leaking a dependency through a re-export — a bug to fix at the source.

verify: format, lint, typecheck, 232 tests, build.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 22:07:23 +00:00
2026-02-26 19:29:55 +01:00

Botsmann

Domain-specialized AI professionals, not another generic chatbot wrapper.

License: MIT TypeScript Next.js Live


The Professionals

Six built-in specialists. Each with scoped knowledge, calibrated personality, and domain-specific system prompts.

Professional Domain Specialty
Lex Legal Contract review, case analysis, regulatory compliance
Imhotep Health Evidence-based insights, research assistance
Nerd Research Systematization, web scraping, discovery
Heidi Language German/Swiss German, translation, culture
Muse Art Style analysis, composition, art history
Trident Business Project management, technical guidance

SSOT: data/bots.ts. Each bot defines system_prompt, expertise[], interests[], communicationStyle (formality/verbosity/empathy), navConfig, and display metadata. Document access is scoped per professional -- Lex sees legal, business, and general docs only.


Architecture

Multi-LLM Routing

Three-tier provider strategy with graceful fallback:

Priority Provider Model Cost
1 Ollama (local) llama3.2:latest Free, self-hosted
2 Groq (cloud) llama-3.1-8b-instant Free tier
3 OpenRouter (cloud) Claude 3.5 Sonnet, GPT-4, Gemini, Grok, Llama, Mistral Paid

Local first, free cloud second, paid cloud last. Users can override via settings. If a provider key is invalid, the system falls back silently to the next tier.

Entry point: lib/llm-client.ts -- generateWithBestProvider() handles selection, timeout (30s), and fallback logic.

RAG Knowledge Retrieval

Zero-cost client-side embeddings with server-side semantic search.

  • Embeddings: Xenova/all-MiniLM-L6-v2 (384-dimensional) via Transformers.js -- runs entirely in the browser, no API calls
  • Chunking: 500-token chunks, 50-token overlap, sentence-aligned boundaries
  • Search: supabase.rpc('match_documents') using pgvector cosine similarity
  • Context limits: 8000 chars for RAG chat, 4000 for professional chat
  • Sources: Returned with document name, preview snippet, and similarity score
  • Timeout: 8s for embedding generation

Privacy Model

Every table enforces Row Level Security. No exceptions.

  • User documents isolated by user_id -- no cross-user data leakage
  • API keys stored encrypted per-user
  • Four-layer prompt injection defense:
    1. sanitizeSystemPrompt() -- prevents instruction override
    2. sanitizeUserMessage() -- removes malicious payloads
    3. sanitizeConversationHistory() -- validates message format
    4. wrapUserContext() -- XML-like delimiters separate data from instructions

Custom Bot Creation

Users build their own specialists:

  • Templates: Memorial, historical, functional, magical, helper
  • Personality: Big Five trait sliders with full editor
  • Knowledge: Upload text, audio, video, images as a custom knowledge base
  • System prompts: Fully user-defined
  • Entity levels: Spark, Aware, Learned, Wise, Evolved, Transcendent

API Design

Standardized response format (SSOT: lib/api/responses.ts):

// Success
{ success: true, data: {...}, meta?: { total, page } }

// Error
{ success: false, error: "Message", details?: [...] }

Rate limits: 20 req/60s for chat, 15 req/60s for professional chat.


Tech Stack

Layer Technology
Frontend Next.js 16, React 19, TypeScript 5, Tailwind CSS + DaisyUI 5
LLM Groq, OpenRouter (100+ models), Ollama (local)
Database Supabase PostgreSQL 15 + pgvector
Embeddings Transformers.js (all-MiniLM-L6-v2, 384d)
Auth Supabase Auth + Row Level Security
Email AWS SES
Deployment Self-hosted on Hetzner (behind Caddy); GitHub Actions CI

Quick Start

Prerequisites

  • Node.js 18+
  • A Supabase project with pgvector enabled
  • At least one LLM provider key (Groq is free)

Setup

git clone https://github.com/your-org/botsmann.git
cd botsmann
npm install

Environment

cp .env.example .env.local

Required variables:

NEXT_PUBLIC_SUPABASE_URL=your-supabase-url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
GROQ_API_KEY=your-groq-key

Optional (for multi-model support):

OPENROUTER_API_KEY=your-openrouter-key
OLLAMA_BASE_URL=http://localhost:11434

Optional (visitor feedback FAB — must be set at next build, not only at runtime):

FLEETCROWN_FEEDBACK_TOKEN=fcw_…

Run

npm run dev

Open http://localhost:3000.


Project Structure

botsmann/
  app/                    # Next.js 16 app router
    api/                  # API routes (thin HTTP layer)
    (routes)/             # Page routes
  components/             # UI components (no business logic)
  data/
    bots.ts               # SSOT: professional definitions
  hooks/                  # Data fetching, state management
  lib/
    api/
      responses.ts        # SSOT: API response format
    llm-client.ts         # Multi-provider LLM routing
    embeddings/           # Transformers.js integration
    security/             # Prompt injection defense layers
  public/                 # Static assets
  supabase/
    migrations/           # Database schema + pgvector setup

License

MIT

Languages
TypeScript 89.7%
HTML 3.6%
PLpgSQL 2.2%
JavaScript 1.6%
Python 1.3%
Other 1.6%