Mirabelle AI — LLM Gateway & Evaluation Testing Guide¶
Status: Implemented (Nov 2026). Source:
files/mirabelle/gateway.py,files/scripts/mirabelle_eval.py
This page is the testing guide for the Mirabelle AI assistant's first production AI slice: the provider-neutral LLM gateway (OpenRouter + the established local Ollama) and the golden-conversation evaluation harness. It tells you how to configure the chat model, what the guardrails are, and — most importantly — how to run and extend the evaluation baseline before and after any model change.
What this slice is (and is not)
This is the FIRST slice of the AI architecture: one representative in-app planner workflow (the Mirabelle chat), two providers (the one the team can use today — OpenRouter — plus the existing Ollama), explicit model selection, bounded retries, audit telemetry, and a repeatable evaluation baseline. Not in this slice: REST AI endpoints, Teams/Slack/email channels, RAG, write actions, approval cards, additional providers, spend dashboards, token budgets. The MCP server — which lets other AI apps read planning data and, with a scope the planner grants, act on the review queue; and which Mirabelle itself uses to call registered MCP servers — is separate from this slice and from its evaluation baseline: see the Mirabelle AI chapter and the MCP server reference.
Overview¶
The chat path is unchanged in shape — question → retrieval → SQL generation → deterministic guardrails → read-only execution → explanation — but the model call now travels through a small provider-neutral gateway:
flowchart LR
SG["sql_generator / explainer<br/>(prompt assembly — provider-agnostic)"]
GW["gateway.complete()<br/>explicit provider · bounded retry · redaction"]
OL["Ollama adapter<br/>(local, streaming, byte-identical)"]
OR["OpenRouter adapter<br/>(Bearer key, usage reported)"]
SG --> GW --> OL
GW --> OR
- Explicit selection, no fallback chain. The provider/model is chosen per turn — env
defaults, overridden by the tenant's
aiparameter set. Selecting OpenRouter without a key fails the turn with an honest error; it NEVER silently falls back to Ollama. - Transient vs permanent errors. Rate limits (429), timeouts and 5xx are retried a bounded
number of times (default 3 attempts) with exponential backoff and
Retry-Afterrespected. Permanent errors (401/400/404, unknown provider, missing credential) fail immediately. - Secrets stay secret. The OpenRouter key is write-only in settings (masked
********on every GET via the shared parameter-secrets redaction), never logged, never in error text (errors are scrubbed against the key value). - Usage telemetry. Each turn reports
llm: {provider, model, usage}in the chat response; the provider/model, latency, token usage and outcome are audit-logged per turn.
Configuration¶
Two surfaces, in precedence order (tenant ai parameter set wins over env defaults):
| Setting | ai parameter set key |
Env default | Meaning |
|---|---|---|---|
| Provider | chat_provider |
MIRABELLE_LLM_PROVIDER (ollama) |
ollama | openrouter — explicit, no fallback |
| Model | chat_model |
MIRABELLE_LLM_MODEL / MIRABELLE_OPENROUTER_MODEL |
The exact ID or tag for the selected provider. Blank uses the deployment default. |
| OpenRouter URL | openrouter_url |
MIRABELLE_OPENROUTER_URL (https://openrouter.ai/api/v1) |
API base |
| OpenRouter key | openrouter_api_key |
OPENROUTER_API_KEY |
Secret — masked on GET, restored on PUT |
| SQL visibility | sql_visibility |
MIRABELLE_SQL_VISIBILITY (all) |
all = everyone sees the executed SQL (the established transparency); admin = admin/superadmin roles only |
| Retry budget | — | MIRABELLE_LLM_MAX_ATTEMPTS (3), MIRABELLE_LLM_RETRY_BACKOFF_S (1.5) |
Bounded transient retry |
Administrators edit Settings → AI → Chat LLM connection. See the setup steps for each
provider. Untouched masked keys keep their stored
value. /api/mirabelle/status reports the active provider and model and, for OpenRouter, whether
a key is configured; it does not return the key or validate it.
The server stores provider-specific model history in chat_model_history. GET and PUT return it
as model_history alongside the editable parameters_set. Legacy openrouter_model values are
read to preserve existing choices and are replaced by the new shape on the next settings save.
When changing the provider, include chat_model explicitly; "" selects the deployment default.
OpenRouter sends tenant data off-server
The local Ollama deployment keeps all data on-premise. Selecting OpenRouter sends the assembled prompt (schema context + your question + result samples) to an external API. The SQL executed and the data returned remain governed by the same read-only, tenant-scoped connection as before.
The guardrails¶
Both providers use the same schema metadata, synonym map, column validator, and read-only
executor (readonly=2). query_scope.py derives scope from the current question and the
selected pipeline, not from generated SQL or chat history. It applies a filter per ClickHouse
table scan. A query that cannot be scoped never goes to the executor. By default, Standard speed
allows up to two SQL generation attempts in total. A permanent provider failure (e.g. missing
key) exits the loop after one attempt.
Per-turn audit rows (sys_audit_log, entity mirabelle_chat) record provider, model, usage,
attempts, row count, latency and outcome — never the question text, the SQL, or any credential.
The evaluation harness¶
files/scripts/mirabelle_eval.py runs the golden planner workflow from
files/mirabelle/eval_conversations.py — three cases covering one real workflow:
| # | Case | Workflow step | What it proves |
|---|---|---|---|
| 1 | planner-identify-lowfill |
Identify an exception ("lowest fill rate?") | The active pipeline and its MEIO scenario are enforced even when the model drafts a different scenario filter; answer quotes the fixture numbers |
| 2 | planner-impact-shortage |
Explain its impact ("projected shortage next 4 weeks?") | Planning-date substitution ({planning_date} → the pinned business date); wrong MEIO id on a SUPPLY table corrected; numeric grounding (the answer's total = the deterministic sum) |
| 3 | planner-grounded-return-netting |
Grounded planning question ("firm return orders netted?") | Netting uses the linked series scenario, not the old scenario-0 writer; planning context reaches the model |
Offline mode (default) — no infrastructure¶
The LLM is scripted (it emits the case's scripted_sql, deliberately carrying the classic
model mistakes) and the executor is stubbed with deterministic fixture rows. Everything between
them is the real code path: scenario-map resolution, planning-date resolution, all
deterministic fixers, the validator, the bounded retry loop, deterministic numeric aggregation and
the answer-shape checks. Exit code 0 = all pass; 1 = failures (each named); 2 = usage error.
This is the mode the pytest suite runs — and it is a plumbing/guardrail proof, not a model
reliability claim. A passing offline report says the deterministic layers work; it says nothing
about any model. files/tests/test_mirabelle_query_scope.py additionally executes the rewritten
queries over synthetic rows from multiple pipelines and scenarios, including joins and unions.
Live mode — real tenant, explicit model¶
$env:OPENROUTER_API_KEY = "sk-or-..."
& files\venv\Scripts\python.exe files\scripts\mirabelle_eval.py --live `
--db gps_3 --pipeline-id 2 `
--provider openrouter --model anthropic/claude-sonnet-4
--provider and --model are required for live runs: the evaluated model is always explicit,
the CLI selection wins over the tenant's ai set, and a mismatch is reported as a failure. Live
checks per case (live_expect):
- SQL pattern checks — must/must-not fragments,
{pipeline_id}substituted from the CLI; - tables used and minimum row counts (execution success);
- non-empty answers;
- numeric grounding — cases with
reference_value_sqlrun a reference query against the tenant and require the answer to quote the DATABASE's value; an invented number fails the case.
Extending the baseline¶
- Append cases to
GOLDEN_CONVERSATIONSinfiles/mirabelle/eval_conversations.py, or - pass extra JSON case files (same schema):
--cases my_cases.json(repeatable), or - run a subset:
--case <id> --case <id>.
Each case needs: id, workflow_step, question, and for offline runs scripted_sql +
fixture_rows/fixture_columns + expect; for live runs live_expect. A good case reproduces a
REAL planner question and pins the guardrail that makes its answer trustworthy.
Test catalog¶
| Suite | What it covers |
|---|---|
files/tests/test_mirabelle_gateway.py |
OpenRouter request/response shaping, transient vs permanent classification, Retry-After, bounded backoff, secret redaction in errors, settings resolution (env/DB/sentinel/unknown provider), Ollama wire-identity, SQL visibility gate roles |
files/tests/test_mirabelle_chat_gateway.py |
Unconfigured provider → honest error, one attempt, no fallback; llm telemetry block on success and failure |
files/tests/test_mirabelle_eval_harness.py |
All golden cases pass offline; the checks genuinely FAIL on broken expectations; CLI exit codes; JSON case-file expansion; live reference-value grounding checks |
files/tests/test_mirabelle_review_fixes.py |
Pre-existing guardrail regressions (fixers, aggregates, num_ctx sharing — updated to the gateway shape) |
files/tests/test_chat_feedback_ddl.py |
The three copies of the rating table's DDL agree; every constraint the store relies on, on a real PostgreSQL; a pipeline delete keeps the ratings |
files/tests/test_chat_turns.py |
The server's copy of a turn: owner, expiry, bounded memory |
files/tests/test_chat_feedback_store.py |
Text cleaning, SQL templates, rate / change / take back, review, export, and which approved rows reach the prompt (real PostgreSQL) |
files/tests/test_chat_feedback_retrieval.py |
Approved feedback reaches the prompt in the right place; a failed read costs the turn nothing; what a finished turn hands to the rating endpoint |
files/tests/test_chat_feedback_router.py |
The HTTP surface: who may rate and review, audit rows without text, the rate limit, one transaction per change |
files/tests/test_chat_feedback_endpoint.py |
The chat endpoint keeps its own copy before the SQL gate and never returns the internal payload |
files/frontend/src/utils/chatFeedback.test.js |
The rules of the thumbs and of the review screen (npm run test:desktop) |
files/scripts/chat_feedback_browser_check.py |
A real Chromium against the dev front end with the rating routes stubbed: thumbs, reason list, server refusals, reload, the review screen, both themes |
files/tests/test_guide_chunker.py |
"Ask the guide": the markdown reader (anchors equal python-markdown's, each markup construct, wrapped lines joined, fences, windows, links, exclude_docs) and its parity with python-markdown and mkdocs on the REAL docs tree |
files/tests/test_guide_service.py |
The guide index: availability, the background build, the vector cache, search, the gate, extract and generate answers (scripted model: numbers and length checks, sources line, token handling), the answer-mode setting (real PostgreSQL), the encoder's contract |
files/tests/test_guide_router.py |
The HTTP surface: who may ask, 409 while not ready, the rate limit, one generated answer at a time, audit rows without text, every connection closed |
files/tests/test_guide_golden.py |
The gate and the ranking on 23 documented, 6 undocumented and 4 data questions over the real docs (needs the real model; skipped without it) |
files/frontend/src/utils/guideChat.test.js |
The panel's rules for the guide: status line, failures, what an answer shows (npm run test:desktop) |
files/scripts/guide_browser_check.py |
A real Chromium against the dev front end with the guide routes stubbed: the switch, answer card, ellipsis marks, every refusal, both themes |
Manual test walkthrough (before accepting a model change)¶
- Baseline:
python files/scripts/mirabelle_eval.py→ all cases pass (guards intact). - Configure the candidate: Settings → AI → Chat LLM connection. For OpenRouter, select the provider, enter the exact ID in Model, and set the write-only key. Wait for autosave and click Test connection. A successful probe checks reachability, not key validity.
- Live evaluate:
python files/scripts/mirabelle_eval.py --live --db <tenant> --pipeline-id N --provider openrouter --model <id>→ review the per-case report. - In-app spot check: ask the three workflow questions and use View SQL to verify the
submitted queries and their scoped filters. Under
sql_visibility: admin, a non-admin sees the restriction, not the SQL. Use How was this answered? to check the tables and compare the answer's numbers with the result table. - Audit check:
sys_audit_logrows formirabelle_chatcarry provider/model/usage/outcome; confirm no question text, SQL or key appears in any audit row or log line. - Rollback: set
chat_provider: ollama— the local deployment is the default and the byte-identical baseline.
Checking the guide mode before accepting a model¶
Ask the guide needs no model in its default mode. To judge a model for the optional summaries
(Settings → AI → Ask the guide - answers → Sections plus a short summary), ask the same documented
questions in both modes and compare: the summary must agree with the sections shown, must not contain
a number that is not in them, and a documented topic answered not documented is the safe failure.
A small local model is cautious; a strong cloud model writes the better summaries. The sections are
always shown, so a withheld or wrong summary never hides the guide's own text.
Key files¶
| File | Role |
|---|---|
files/mirabelle/gateway.py |
Provider-neutral gateway: LLMRequest/LLMResponse, provider registry + capability data, bounded retry, RuntimeSettings resolution (env ← tenant ai set) |
files/mirabelle/ollama.py |
Streaming Ollama caller (unchanged wire format; optional usage capture) |
files/mirabelle/sql_generator.py / explainer.py |
Prompt assembly — routed through the gateway, provider-agnostic |
files/mirabelle/eval_conversations.py |
The golden planner workflow + fixtures |
files/scripts/mirabelle_eval.py |
The evaluation harness (offline + live) |
files/api/main.py |
ai parameter-set defaults, per-turn audit, SQL visibility gate |
files/mirabelle/turns.py / files/mirabelle/feedback.py |
The rateable-turn registry and the rating store (approval rules, example matching) |
files/api/chat_feedback_router.py |
The rating and review routes |