Files
CatoandClaude Opus 5 d050d1589c feat(health): /api/health/ai — make the 2026-08-28 outage observable BEFORE a user hits it (#184)
On 2026-08-28 /api/health reported "healthy" while every AI feature on
this site was failing on an invalid Groq key. Carrying `llm` in that body
fixed the REPORTING. It did not make the state observable before a user
hit it, because nothing calls a provider until somebody uses the bot — so
straight after a deploy the field reads "unknown", and unknown is what it
stays.

  GET /api/health/ai            free. What the last real call did.
  GET /api/health/ai?probe=1    a real call. 200 or 503. Needs the secret.

Opposite contract to /api/health on purpose: that route is LIVENESS and
must stay 200 while the LLM is down, because restarting does not fix an
expired key and failing on it would get a healthy process killed. This
one is the inverse, so an uptime monitor can page on a real AI outage
without paging on every deploy.

It probes THIS app's chain: `ask` (ai-kit 0.15.0) calls
generateWithBestProvider, the same function the chat routes use. A probe
built from its own provider list would test a path nothing else takes and
would drift from this one the first time the chain changed.

The secret is a GETTER — the handler is built once and reused, so a
captured string would be whatever the environment held on the first
request: un-rotatable without a restart, and untestable.

TWO THINGS THE TESTS TAUGHT ME, both about this app rather than the
probe:

  - generateWithBestProvider goes through getServerEnv(), which validates
    the WHOLE server env and throws on the first missing var. A probe
    test that sets only the AI keys fails on SUPABASE_SERVICE_ROLE_KEY,
    nowhere near the chain.
  - Ollama is tried first and its availability is a LIVE PING, so a fetch
    mock that answers every URL makes a local runtime appear to exist and
    win the chain. The mock now refuses :11434, which is prod's real
    shape — and the "which vendor served it" assertion looks at every
    call rather than calls[0], because calls[0] is that ping.

verify green — 301 tests.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 14:56:46 +00:00

67 lines
3.4 KiB
TypeScript

/**
* Can this deployment reach a model RIGHT NOW?
*
* `/api/health` carries `llm` as an informational field, and that field reports
* what happened the LAST time something called a provider. Straight after a
* deploy it is `"unknown"`, and unknown is what it stays until real traffic
* arrives — so the one question a deploy needs answered ("did I just ship a
* working AI path?") is exactly the one it cannot answer.
*
* This repo already knows the cost of that gap. On 2026-08-28 `/api/health`
* said "healthy" while every AI feature on the site was failing on an invalid
* Groq key. Adding `llm` to the body fixed the reporting; it did not make the
* state OBSERVABLE before a user hit it, because nothing calls a provider until
* somebody uses the bot.
*
* ── It probes THIS app's chain ───────────────────────────────────────────────
* `ask` calls `generateWithBestProvider`, the same function the chat routes
* use. A probe built from its own provider list would test a path nothing else
* takes and would drift from this one the first time the chain changed.
*
* ── Gating and caching are ai-kit's ──────────────────────────────────────────
* A probe spends real tokens from the same free budget the bot draws on, so it
* runs only on `?probe=1` WITH the secret, a success is cached ten minutes, and
* a failure is never cached. With no secret configured the route answers 501
* rather than becoming an open endpoint that can spend money.
*/
import { createAiHealthHandler } from '@bitbaum/ai-kit';
import { generateWithBestProvider } from './llm-client';
import { llmHealthTracker } from './llm-health';
/**
* Built lazily. Next evaluates module-level code during the BUILD, where the
* runtime's keys are absent — an eagerly-built handler would capture that empty
* environment and report a dead engine forever on a deployment whose keys are
* fine.
*/
let handler: ((request: Request) => Promise<Response>) | null = null;
export function aiLivenessHandler(request: Request): Promise<Response> {
handler ??= createAiHealthHandler({
// A getter, not a value: the handler is built once and reused, so a plain
// string would be whatever the environment held on the first request —
// un-rotatable without a restart, and untestable.
secret: () => process.env.AI_PROBE_SECRET,
// The tracker the real chat writes to, so one probe also answers the next
// ordinary /api/health poll instead of dying with this request.
health: llmHealthTracker,
ask: async () => {
const result = await generateWithBestProvider(
[
{ role: 'system', content: 'Answer with a single word, no punctuation.' },
{ role: 'user', content: 'What colour is a clear midday sky? One word.' },
],
// Generous on purpose: the chain leads with reasoning models, which
// spend this budget thinking before emitting a visible token, and an
// empty completion is treated as a failure. A mean budget would make a
// healthy deployment report itself dead.
{ maxTokens: 256, temperature: 0 },
);
return { text: result.content, id: `${result.provider}/${result.model}` };
},
});
return handler(request);
}