Skip to content
kherryPublic

About

Automatic LLM Router - The AI engine powering GreyRock

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Multi-LLM Chat

Self-hosted chat over multiple LLM providers, with automatic model routing that enforces permissions and budget in code rather than in a prompt.

Built from three specifications — architecture.md, routing-design.md and api-spec.md — which are the source of truth. Where this README and a spec disagree, the spec wins and the README is wrong.

Status

Phase Scope State
0 Foundation: compose, migrations, config, logging, health, CI done
1 Data layer: 17 tables, migrations, system group seeding done
2 Auth and permissions: OIDC, superuser, sessions, resolver done
3 Provider adapters: streaming, typed errors, breaker done
4 Chat core: CRUD, WS gateway, streaming, resume, locking done
5 Router: pipeline, selector, fallback, auto-titling done
6 Frontend: auth, shell, composer, telemetry, settings, admin partial
7 Admin: scoped endpoints, guards, audit, analytics, UI partial
8 Lifecycle next

First run

cp .env.example .env
python -c "import secrets; print(secrets.token_urlsafe(48))"   # SECRET_KEY
python -c "import secrets; print(secrets.token_urlsafe(48))"   # ENCRYPTION_KEYS
$EDITOR .env
make up

The API is on http://localhost:8000, the app on http://localhost:5173, and the OpenAPI docs on http://localhost:8000/docs outside production.

On the first boot with an empty database, a superuser is created and its password is written to the API logs once, at WARNING, inside a delimited block:

====================================================
SUPERUSER CREATED — this password is shown ONE TIME
username: admin
password: <generated>
====================================================

Capture it then. It is hashed with argon2id and is not recoverable from the database.

If you missed it, or you have booted before and the banner did not reappear — it only ever prints on the boot that creates the account:

docker compose exec api app superuser reset-password

That regenerates the password, prints it once, and requires a change at next sign-in. There is deliberately no HTTP endpoint for it.

Subsequent boots never regenerate, never overwrite and never re-log. The bootstrap holds a Postgres advisory lock, so replicas starting at the same moment cannot create two accounts or print two different passwords.

Local development without Docker

cd api && python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
alembic upgrade head
uvicorn app.main:app --reload

cd web && npm ci && npm run dev

Postgres and Redis still need to be running; docker compose up postgres redis starts just those.

Making the deployment usable

A fresh install has no models, so nothing can be sent. Sign in as the superuser and open Admin → Providers & models:

  1. Add a provider (name, optional base URL, API key).
  2. Add a model on it — model key, display name, tier, context window, prices. Tick "use as the router's classifier" on a cheap one, or auto mode falls back to the default tier on every message.
  3. Use Test connection: a one-token probe that catches a typo'd model key before a user meets it as a runtime failure.
  4. Open Groups & users and grant the model to a group.

The model appears in the composer dropdown immediately — permissions are cached for five minutes but invalidated eagerly on every grant.

Troubleshooting first run

"Reconnecting…" that never resolves. The chat socket connects to /api/v1/ws, which the Vite dev proxy must be told to upgrade (ws: true on the /api rule). If you have customised vite.config.ts, check that first — REST will keep working while the socket silently fails.

No superuser password in the logs. It prints only on the boot that creates the account. To reissue it:

docker compose exec api app superuser reset-password

Identity providers

Setup for Authentik and Microsoft Entra ID, including the one setting in each that silently breaks group sync, is in docs/identity-providers.md.

Environment

Everything is in .env.example with inline notes. List-valued variables (CORS_ORIGINS, ENCRYPTION_KEYS) accept a bare value, a comma-separated list, or a JSON array — all three are tested through the environment, not just through the settings constructor. Four entries deserve reading before a production deploy:

  • SECRET_KEY signs access tokens. Rotating it logs everyone out.
  • ENCRYPTION_KEYS encrypts provider API keys and the OAuth client secret at rest. The first key encrypts, all keys decrypt, so rotation is: prepend a new key, re-save the affected rows, drop the old one. Lose every key and every stored provider credential is gone — they are not recoverable from a backup of the database alone.
  • SUPERUSER_ENABLED=false closes the local login path without touching the account, its group memberships or its conversations.
  • RETENTION_PURGE_DAYS=0 means never purge, and is the shipped default. Archiving at 30 days is on; permanent deletion is an explicit operator choice. See DECISIONS.md D-004 for what happens when this changes after the fact.

Layout

api/
  app/
    config.py          every tunable, typed, in one place
    db.py              async engine, session factory, naming conventions
    redis_client.py    live state only — never the system of record
    core/
      context.py       ULID request ids in a contextvar
      logging.py       structured logs carrying request_id
      errors.py        api-spec §7 taxonomy and the one error envelope
      middleware.py    request id assignment, access logging
    api/v1/            REST surface; feature routers mount here per phase
    models/            ORM: enums, identity, catalog, chat, operations
    auth/              permissions resolver, cache, tokens, OIDC sync
    admin/             escalation guards, in-transaction audit logging
    providers/         adapter contract, Anthropic + OpenAI, circuit breaker
    chat/              costs and ledger, locks, delta buffer, generation runner
    router/            task profile, deterministic selector, pipeline
    bootstrap/         idempotent first-boot steps
    cli.py             operator commands that must not be HTTP endpoints
  alembic/             migrations
  scripts/             dump_openapi.py — the frontend's type source
  tests/
    invariants.py      the twelve invariants, as checked data
    db.py              migration-built schema fixtures
    data/              schema and seed tests
web/
  src/api/             generated types + the fetch client
  src/lib/             pure logic: timestamps, money, keyboard, grouping
  src/ws/              socket client with seq tracking and resume
  src/components/      composer, message list, telemetry, panels
  src/store/           Zustand: drafts, panel state, expanded debug bars

Testing

make check       # lint, types and both test suites
make test
make smoke       # boot the stack and verify first-run behaviour

make smoke is the one that catches deployment-shaped problems: it runs docker compose up, waits for readiness, and checks that the generated superuser password actually signs in. CI runs the same checks as a third job, because a green test suite has twice now coexisted with a stack that would not start.

Backend tests run against a real Postgres and Redis, in CI as well as locally. This is deliberate: advisory locks, SET NX generation locks and refresh-token rotation races are precisely the behaviours a mock reproduces incorrectly. Provider HTTP calls are stubbed at the transport layer with respx, so the adapter code under test is the real thing.

tests/invariants.py registers the twelve non-negotiable invariants and the named test that owns each one. CURRENT_PHASE gates enforcement: once a phase ships, deleting or renaming its invariant test breaks the build.

The routing selector, permission resolver and cost calculation carry a 100% branch floor. They are small, pure and load-bearing, and every serious bug this system can have passes through one of them.

Conventions worth knowing before contributing

  • Money is Decimal end to end, NUMERIC in Postgres, decimal strings on the wire. A float anywhere in a cost path is a defect, not a style choice.
  • All timestamps are TIMESTAMPTZ in UTC. The client formats to local time.
  • No any in frontend application code, and payload types are generated from api/openapi.json rather than written by hand. CI diffs both artifacts.
  • Access tokens live in memory; refresh tokens live in an httpOnly cookie. ESLint bans the localStorage global to keep it that way.
  • The WebSocket is authenticated by ticket exchange, never a JWT in the query string — query strings land in access logs and browser history.
  • IdP endpoints must be https and ID tokens are fully validated: issuer, audience, expiry, nonce and signature against the IdP's JWKS.

About

Automatic LLM Router - The AI engine powering GreyRock

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages