Plain language first, the code one click away
How it works
The short version: the 429s come from sending more tokens in one minute than the plan allows, so the fix is to queue and retry on the provider's schedule and, above all, to send smaller prompts. Exact lines are kept by never letting the model write them. And nothing ships unless the 30-question test still passes. The code under each section is read from the source at build time.
What to check first for the 429s
The post says about one request in three fails when three arrive together, with prompts of about 14,500 tokens. That pattern points at the tokens-per-minute limit before anything else.
What I would check, in order:
- Read one failed response in full. The 429 body and the
x-ratelimit-*headers say whether the limit hit was tokens per minute or requests per minute, the limit itself, how much is left, and when it resets. If the platform's wrapper drops those details, log them before they are lost. - Compare tokens per minute with prompt size times concurrency. In this simulation, each request reserves its prompt plus its max output tokens when it arrives. Three requests of 14,500 + 500 tokens need 45,000 tokens at once. On a 30,000 tokens-per-minute limit, two fit and the third is rejected: exactly one in three. The 30,000 is an assumption;
x-ratelimit-limit-tokenson one of your 429s confirms the real number. - Check concurrency and retries. Are requests sent the moment they arrive, with no queue? Is there a retry, and does it wait for
retry-afteror fire again immediately? Rejected requests still count against requests per minute, so fast retries make it worse. - Find out whose limit it is. The app calls OpenAI through Replit's AI integration, so first confirm whether the 429 comes from Replit's proxy or from an OpenAI account you control. The answer decides the fix: if the limit belongs to the integration, you may not be able to raise it yourself, and moving to your own key with a known tier may be the real change. Every rep, and every server instance, shares whichever budget that is.
- Check max_tokens. A generous value reserves budget the short coaching answer never uses.
Fixing the 429s reproduces this with a simulated provider that enforces both limits and returns 429 with retry-after and x-ratelimit-* headers.
The fix: wait for budget, retry on the provider's schedule
Token-aware admission. Before sending, the client estimates the request's tokens and waits in a local token bucket that mirrors the provider's limit. A request the provider would reject is never sent; it waits its turn instead.
Show the code: token-aware admission
/** Wait until the local budget says the provider will accept this request, then reserve it. */
async function waitForBudget(request: CoachRequest, cost: number, deadline: number, emit: Emit) {
for (;;) {
const waitMs = Math.max(tokens.msUntil(cost), requests.msUntil(1));
if (waitMs === 0) {
tokens.tryTake(cost);
requests.tryTake(1);
return;
}
if (clock.now() + waitMs > deadline) throw new BusyError(waitMs);
emit({ type: "queued", id: request.id, t: clock.now(), reason: "tokens", waitMs });
await clock.sleep(waitMs);
}
}Backoff with full jitter that honors retry-after. When a 429 still gets through (another instance or another app on the same key used the budget), the client waits at least as long as the provider asked, never less, and caps the number of retries.
Show the code: backoff with full jitter
/** Full jitter: wait a random time between 0 and the exponential ceiling. */
export function fullJitterDelay(attempt: number, policy: BackoffPolicy, random: Random): number {
const ceiling = Math.min(policy.capMs, policy.baseMs * 2 ** attempt);
return Math.floor(random() * ceiling);
}
/**
* The provider's retry-after is a floor: retrying sooner only burns another
* request. A little jitter on top stops clients that got the same hint from
* retrying in lockstep. Without a hint, fall back to full jitter.
*/
export function retryDelay(
attempt: number,
policy: BackoffPolicy,
random: Random,
retryAfterMs?: number,
): number {
if (retryAfterMs !== undefined && Number.isFinite(retryAfterMs) && retryAfterMs >= 0) {
return Math.ceil(retryAfterMs) + Math.floor(random() * policy.hintJitterMs);
}
return fullJitterDelay(attempt, policy, random);
}Show the code: the retry loop
export async function withRetry<T>(
attemptFn: (attempt: number) => Promise<T>,
{ policy, random, clock, deadline, onRetry }: RetryOptions,
): Promise<T> {
for (let attempt = 0; ; attempt++) {
try {
return await attemptFn(attempt);
} catch (error) {
if (!(error instanceof RetryableError)) throw error;
if (attempt >= policy.maxRetries) throw new RetriesExhaustedError(attempt + 1, error);
const delayMs = retryDelay(attempt, policy, random, error.retryAfterMs);
if (deadline !== undefined && clock.now() + delayMs > deadline) {
throw new DeadlineExceededError(delayMs, error);
}
onRetry?.({ attempt, delayMs, error });
await clock.sleep(delayMs);
}
}
}Admission is single file, with a concurrency cap. While one request waits out a retry-after, nobody behind it sends a request that would only get the same 429.
Show the code: single-file admission
// Single-file admission: while one request waits out a retry-after,
// nobody behind it sends (they would only get the same 429).
const leaveLine = await admissionLine.acquire();
let response: Response;
try {
response = await withRetry(
async (attempt) => {
await waitForBudget(request, cost, deadline, emit);
leaveBacklog();
attempts++;
emit({ type: "send", id: request.id, t: clock.now(), attempt, estimatedTokens: cost });
const res = await post(transport, url, chatBody(request, model), headers);
if (res.status === 429 || res.status >= 500) {
tokens.refund(cost); // a rejected request is not charged for tokens
syncFromHeaders(res);
const retryAfterMs = parseRetryAfter(res.headers, clock.now());
const message = await readErrorMessage(res);
emit({ type: "rate_limited", id: request.id, t: clock.now(), attempt, status: res.status, retryAfterMs, message });
throw new RetryableError(message, retryAfterMs, res.status);
}
syncFromHeaders(res);
if (!res.ok) throw new Error(await readErrorMessage(res));
return res;
},
{
policy,
random,
clock,
deadline,
onRetry: ({ attempt, delayMs }) => emit({ type: "backoff", id: request.id, t: clock.now(), attempt, delayMs }),
},
);
} finally {
leaveLine();
}Fail fast, with a clear message. If the queue ahead already needs more budget than a rep can reasonably wait for (45 seconds), the client says so at once. Every failure leaves the server as a clean event: error with a code and a retry hint, which the app turns into “Lots of reps are asking right now. Tap Try again in about 20 seconds” instead of “The coaching response could not finish”. The message promises only what happens: nothing is saved or retried behind the rep's back.
Show the code: failing fast
// Fail fast: if the line ahead already needs more budget than this rep can wait for, say so now.
const projectedMs = tokens.projectedWaitMs(backlog + cost);
if (projectedMs > maxWaitMs) {
return fail({
code: "busy",
retryable: true,
retryAfterMs: projectedMs,
message: `Queue needs about ${Math.round(projectedMs / 1000)} s of token budget before this request`,
userMessage: calmMessage(projectedMs, maxWaitMs),
});
}Show the code: the try-again message
if (error instanceof BusyError || error instanceof DeadlineExceededError || error instanceof RetriesExhaustedError) {
const retryAfterMs =
error instanceof BusyError
? error.retryAfterMs
: error instanceof DeadlineExceededError
? error.waitMs
: error.lastError.retryAfterMs;
return fail({
code: "busy",
retryable: true,
retryAfterMs,
providerStatus: error instanceof BusyError ? undefined : 429,
message: error.message,
userMessage: calmMessage(retryAfterMs, maxWaitMs),
});
}Provider setup for a group of reps
- Measure the prompt, then trim it. The biggest lever, if the 14,500 tokens are mostly pasted reference text. That is a hypothesis: a token breakdown of one real prompt confirms it. If so, sending the matched section and top lines (a target of about 4,000 tokens) lets the same plan serve about three times as many questions a minute, and answers start sooner. The trim ships only if the 30-question score holds; the last bug silently cut content, so this one is gated.
- Size the limit for the busiest minute. Reps asking at once × (prompt + max output). Ten reps with 4,500-token requests need 45,000 tokens per minute; with 15,000-token requests, 150,000.
- Use a key whose limits you know and can raise. Usage tiers go up with account history and spend; confirm the tier for the exact model in use.
- One budget per key. If Replit runs more than one instance of the app, keep the token bucket in the Postgres you already have (or Redis) so the instances share it instead of each assuming the whole budget.
- Put the stable instructions first so the provider's prompt caching can reuse them; it cuts latency and cost.
How the coach keeps the exact lines
The model can't paraphrase a line it never writes. Common questions go to an answer bank first. A keyword group has to pin the situation (“no” with “budget”, not “budget” alone), and a bare topic word counts only when the rep is reporting what the buyer said. Above the threshold, the approved text is returned exactly as stored, then one follow-up: “Want to know why this works?”
Show the code: answer-bank scoring
/**
* A keyword group that pins the situation is strong evidence; a bare topic word
* counts only when the rep reports what the buyer said. Otherwise the question
* must look like a known phrasing.
*/
export function scoreEntry(question: AnalyzedQuestion, prepared: PreparedEntry): BankCandidate {
const base = { entry: prepared.entry, closestExample: prepared.examples[0]?.text ?? "" };
if (channelConflict(question.channel, prepared.channel)) {
return { ...base, score: 0, keywordHit: false, similarity: 0, excluded: "channel" };
}
const all = new Set(question.terms);
const content = new Set(question.content);
let similarity = 0;
let shared = 0;
let closestExample = base.closestExample;
for (const example of prepared.examples) {
const value = dice(content, example.terms);
if (value > similarity) {
similarity = value;
shared = [...content].filter((term) => example.terms.has(term)).length;
closestExample = example.text;
}
}
const hit = (group: string[]) => group.every((term) => all.has(term));
const keywordHit = prepared.groups.some(hit) || (question.buyerVoice && prepared.buyerGroups.some(hit));
// One shared word with a short example ("next" vs "the next step") is not a match,
// unless the question is that example word for word ("I'm too busy right now").
const sameAsExample = shared > 0 && shared === content.size && similarity === 1;
const score = keywordHit ? 0.6 + 0.4 * similarity : shared >= MIN_SHARED_TERMS || sameAsExample ? similarity : 0;
return { ...base, score: Math.round(score * 1000) / 1000, keywordHit, similarity, closestExample };
}
export function matchBank(question: AnalyzedQuestion, config: MatcherConfig = DEFAULT_MATCHER, prepared: PreparedEntry[] = PREPARED): BankMatchResult {
const candidates = prepared
.map((entry) => scoreEntry(question, entry))
.sort((a, b) => b.score - a.score || a.entry.id.localeCompare(b.entry.id));
const [top, second] = candidates;
if (!top || top.score < config.threshold) return { match: null, decision: "below-threshold", candidates };
// A keyword hit beats a look-alike phrasing; two of the same kind this close are a tie.
const tie = second && second.score >= config.threshold && top.score - second.score < config.margin && !(top.keywordHit && !second.keywordHit);
if (tie) return { match: null, decision: "ambiguous", candidates };
return { match: top, decision: "matched", candidates };
}Below the threshold, search runs over individual approved lines, not whole documents, so an objection or email type lands on the exact source line with its citation. Words found in almost every question (“give me a good line”) never count as evidence, a line needs two of the question's words from what its section is about, an email question never gets a call line, and when two sections fit about equally the coach asks which one instead of guessing. When nothing approved fits, it says so.
Show the code: line retrieval
export function retrieveLines(question: AnalyzedQuestion, limit = 5, index = INDEX): RetrievalResult {
const queryTerms = [...new Set(question.content)];
const ranked = scoreLines(question, index);
const top = ranked.find((line) => line.supported) ?? null;
const base = { ranked: ranked.slice(0, limit), terms: queryTerms };
if (!top) {
return { ...base, decision: "none", best: null, alternative: null, reason: queryTerms.length ? "No line shares enough of the question's words with what its section is about" : "No content words to search for" };
}
// The closest rival from a different section that also clears the bar.
const rival = ranked.find((line) => line.supported && line.ref.section.id !== top.ref.section.id) ?? null;
const single = queryTerms.length === 1;
if (rival && (single || (top.score - rival.score) / top.score < CLARIFY_MARGIN)) {
return { ...base, decision: "clarify", best: top, alternative: rival, reason: single ? "One word fits more than one section" : "Two sections fit almost equally well" };
}
return { ...base, decision: "answer", best: top, alternative: null, reason: "Best line clears the bar with a clear margin" };
}If a model writes the reply around that line, a verbatim check confirms the line is still there word for word and restores it if not. Typos are fixed only when nothing matched as typed, and only for words that are not real English (“pirce”, never “bake”).
Show the code: the answer pipeline
export function answerQuestion(question: string, options: CoachOptions = {}): CoachAnswer {
const { useBank = true, matcher = DEFAULT_MATCHER, paraphrase = false, guard = true, pick } = options;
// Search the question as typed first. Typos are fixed only if nothing matched,
// and only words that are not real English are touched ("pirce", not "bake").
let result = route(analyzeQuestion(question), useBank, matcher);
if (!answered(result)) {
const corrected = analyzeQuestion(question, { vocabulary: VOCABULARY, isEnglishWord });
if (corrected.corrections.length) {
const retry = route(corrected, useBank, matcher);
if (answered(retry)) result = retry;
}
}
const { analyzed, bank: bankResult, retrieval } = result;
const trace: CoachAnswer["trace"] = {
terms: analyzed.terms,
content: analyzed.content,
corrections: analyzed.corrections,
bankDecision: bankResult ? bankResult.decision : "skipped",
bankCandidates: (bankResult?.candidates ?? []).slice(0, 4).map((c) => ({
id: c.entry.id,
intent: c.entry.intent,
score: c.score,
keywordHit: c.keywordHit,
similarity: Math.round(c.similarity * 1000) / 1000,
})),
retrievalDecision: bankResult?.match ? "skipped" : retrieval.decision,
retrievalReason: retrieval.reason,
retrieved: retrieval.ranked.slice(0, 4).map((r) => ({ lineId: r.ref.line.id, score: r.score, matchedTerms: r.matchedTerms, preview: r.ref.line.text })),
threshold: matcher.threshold,
};
// 0. The rep picked one of the options offered earlier: answer with exactly that line.
if (pick && CATALOG.lines.get(pick)?.line.kind === "script") {
return lineAnswer(question, getLine(pick), paraphrase, guard, trace, true);
}
// 1. Answer bank: the approved text is returned as stored. No model touches it.
if (bankResult?.match) {
const { entry, keywordHit, score } = bankResult.match;
const ref = getLine(entry.lineId);
return {
question,
path: "answer-bank",
text: ref.line.text,
quote: toQuote(ref),
bank: { id: entry.id, intent: entry.intent, score, via: keywordHit ? "keyword" : "intent", approvedBy: entry.approvedBy, approvedOn: entry.approvedOn },
followUp: { prompt: FOLLOW_UP_PROMPT, why: ref.section.why.text },
guard: { checked: true, ok: true, action: "none" },
trace,
};
}
// 2. Two bank entries fit about equally. The line search breaks the tie only if it
// clearly prefers one of them; otherwise the coach asks which one rather than guess.
if (bankResult?.decision === "ambiguous") {
const [first, second] = bankResult.candidates;
const scores = new Map(scoreLines(analyzed).map((line) => [line.ref.line.id, line.score]));
const [a, b] = [first, second].map((c) => scores.get(c.entry.lineId) ?? 0);
const winner = a >= b ? first : second;
if (Math.max(a, b) > 0 && Math.abs(a - b) / Math.max(a, b) >= BANK_TIE_BREAK) {
const ref = getLine(winner.entry.lineId);
return {
question,
path: "answer-bank",
text: ref.line.text,
quote: toQuote(ref),
bank: { id: winner.entry.id, intent: winner.entry.intent, score: winner.score, via: winner.keywordHit ? "keyword" : "intent", approvedBy: winner.entry.approvedBy, approvedOn: winner.entry.approvedOn },
followUp: { prompt: FOLLOW_UP_PROMPT, why: ref.section.why.text },
guard: { checked: true, ok: true, action: "none" },
trace: { ...trace, bankDecision: "matched", tieBreak: { chosen: winner.entry.id, over: (winner === first ? second : first).entry.id } },
};
}
return {
question,
path: "clarify",
text: CLARIFY_TEXT,
options: [option(getLine(first.entry.lineId)), option(getLine(second.entry.lineId))],
guard: { checked: guard, ok: true, action: "none" },
trace: { ...trace, retrievalDecision: "clarify", retrievalReason: "The line search did not clearly prefer either answer-bank entry" },
};
}
// 3. Retrieval: find the exact source line, then make sure the answer still contains it.
if (retrieval.decision === "answer" && retrieval.best) {
return lineAnswer(question, retrieval.best.ref, paraphrase, guard, trace);
}
// 4. Two sections fit about equally: ask which one rather than guess.
if (retrieval.decision === "clarify" && retrieval.best && retrieval.alternative) {
return {
question,
path: "clarify",
text: CLARIFY_TEXT,
options: [option(retrieval.best.ref), option(retrieval.alternative.ref)],
guard: { checked: guard, ok: true, action: "none" },
trace,
};
}
// 5. Nothing approved fits: say so instead of inventing generic advice.
return { question, path: "no-match", text: NO_MATCH_TEXT, guard: { checked: guard, ok: true, action: "none" }, trace };
}Show the code: the verbatim check
/** Lowercase, drop accents, apostrophes and punctuation, collapse whitespace. */
export function normalizeForCompare(text: string): string {
return text
.normalize("NFKD")
.replace(/[̀-ͯ]/g, "")
.toLowerCase()
.replace(/['‘’`´]/g, "")
.replace(/[^a-z0-9]+/g, " ")
.trim();
}
/** True when `answer` contains `line` word for word, ignoring case, whitespace and punctuation. */
export function containsVerbatim(answer: string, line: string): boolean {
const needle = normalizeForCompare(line);
if (!needle) return false;
return ` ${normalizeForCompare(answer)} `.includes(` ${needle} `);
}The bank stores a line ID, not a copy of the text, so the bank and the documents can't drift apart. Only the newest approved version of each document is searched, and a test fails the build if two current documents share a name, an approved line appears twice, or any approved line can no longer be found: the “content silently blocked” kind of bug.
The document library in Postgres
The demo keeps its documents in memory, but the model is the one your Postgres library needs. Each document has a slug, a version and a status; a partial unique index allows only one approved version per slug, so “one current version of each document, no duplicates” is enforced by the database itself. Approving a new version supersedes the old one in the same transaction. Search runs per line, over current documents only, with section titles and tags weighted above the line text.
The schema below ran against Postgres 17 while this demo was built: the index rejected a second approved version, search returned only current lines, and approval swapped versions in one step.
Show the SQL: db/schema.sql
-- The document library in Postgres: one current version of each document and
-- line-level keyword search. The demo keeps the same model in memory
-- (src/lib/content); this is the shape it maps to on the coach's database.
create table documents (
id bigserial primary key,
slug text not null, -- 'objection-playbook'
code text not null, -- 'OBJ', the prefix of every line ID
title text not null,
channel text not null default 'any' check (channel in ('any', 'call', 'email')),
version int not null,
status text not null default 'draft' check (status in ('draft', 'approved', 'superseded')),
approved_on date,
unique (slug, version)
);
-- One current version of each document: at most one approved row per slug.
create unique index one_current_version on documents (slug) where status = 'approved';
create table lines (
document_id bigint not null references documents (id) on delete cascade,
line_id text not null, -- 'OBJ-1.2': stable, cited in every answer
section text not null, -- 'Price: It costs too much'
tags text[] not null default '{}',
kind text not null check (kind in ('why', 'script')),
body text not null,
primary key (document_id, line_id)
);
-- What a line is searched by: its section title and tags weigh more than the
-- line itself. array_to_string is only STABLE, but for text[] its result never
-- changes, so the function can be IMMUTABLE and back an index.
create function line_search(section text, tags text[], body text) returns tsvector
language sql immutable parallel safe as $$
select setweight(to_tsvector('english', section || ' ' || array_to_string(tags, ' ')), 'A') ||
setweight(to_tsvector('english', body), 'B')
$$;
create index lines_search on lines using gin (line_search(section, tags, body));
-- Approve a new version. The old approved version is superseded in the same
-- transaction, so there is never a moment with two current versions (or none).
create or replace function approve_document(p_slug text, p_version int) returns void
language plpgsql as $$
begin
update documents set status = 'superseded'
where slug = p_slug and status = 'approved' and version <> p_version;
update documents set status = 'approved', approved_on = current_date
where slug = p_slug and version = p_version;
if not found then
raise exception 'No % version % to approve', p_slug, p_version;
end if;
end $$;
-- Line-level keyword search over current documents only: any word may match.
-- The coach then applies its acceptance rules (two topic words, a clear
-- margin) to these rows.
-- Usage: select * from search_lines('they say the price is too high');
create or replace function search_lines(p_question text, p_limit int default 5)
returns table (line_id text, title text, version int, section text, body text, score real)
language sql stable as $$
with q as (
select to_tsquery('english', replace(plainto_tsquery('english', p_question)::text, ' & ', ' | ')) as query
)
select l.line_id, d.title, d.version, l.section, l.body,
ts_rank(line_search(l.section, l.tags, l.body), q.query) as score
from lines l
join documents d on d.id = l.document_id and d.status = 'approved'
cross join q
where l.kind = 'script' and line_search(l.section, l.tags, l.body) @@ q.query
order by score desc, l.line_id
limit p_limit
$$;
The publish gate
Thirty questions, each with the approved line IDs a correct answer must use. The scorer is strict on purpose: the line word for word, or no credit. Alongside them run held-out phrasings and questions that should be declined, so the gate also sees wrong lines, not just misses.
Show the code: the scorer
/**
* On method only if the answer contains an expected approved line word for word
* (after whitespace and punctuation normalization), or quotes the right source line exactly.
* Naming the method, or a close paraphrase, does not count. A question with no
* expected line should be declined: any line at all is a wrong line.
*/
export function scoreAnswer(answer: ScorableAnswer, expected: string[], lines = CATALOG.lines): ScoredAnswer {
const noLine = answer.path === "no-match" || answer.path === "clarify";
if (expected.length === 0) {
if (answer.path === "clarify") return { onMethod: true, outcome: "asked", reason: "Asked which situation instead of answering" };
if (noLine || !answer.quote) return { onMethod: true, outcome: "declined", reason: "Declined, as it should" };
return { onMethod: false, outcome: "wrong-line", reason: `Answered with ${answer.quote.lineId}; it should have declined` };
}
for (const id of expected) {
const ref = lines.get(id);
if (!ref) continue;
if (containsVerbatim(answer.text, ref.line.text)) {
return { onMethod: true, outcome: "on-method", matchedLineId: id, reason: `Contains ${id} word for word` };
}
if (answer.quote?.lineId === id && normalizeForCompare(answer.quote.text) === normalizeForCompare(ref.line.text)) {
return { onMethod: true, outcome: "on-method", matchedLineId: id, reason: `Quotes source line ${id} exactly` };
}
}
if (answer.path === "clarify") {
const optionHit = (answer.options ?? []).some((option) => expected.includes(option.lineId));
return { onMethod: false, outcome: "asked", optionHit, reason: optionHit ? "Asked which situation; the right line was one of the two options" : "Asked which situation; neither option was the expected line" };
}
if (answer.path === "no-match") return { onMethod: false, outcome: "no-line", reason: "Declined: no approved line returned" };
if (answer.quote && !expected.includes(answer.quote.lineId)) {
return { onMethod: false, outcome: "wrong-line", reason: `Used ${answer.quote.lineId}, expected ${expected.join(" or ")}` };
}
return { onMethod: false, outcome: "not-verbatim", reason: "Right idea, but the approved line is not there word for word" };
}Show the code: the gate
/**
* No publish below the threshold, no publish if the score dropped from the last
* approved run, and no publish if more questions get a wrong approved line.
*/
export function gate(run: Partial<EvalRun> & { suite: EvalReport }, baseline?: Baseline): GateDecision {
const { suite } = run;
const reasons: string[] = [];
if (suite.score < suite.threshold) reasons.push(`Score ${suite.score}/${suite.total} is below the threshold of ${suite.threshold}`);
if (baseline && suite.score < baseline.score) reasons.push(`Score dropped from ${baseline.score} to ${suite.score}`);
const wrong = wrongLines(run);
if (baseline?.wrongLines !== undefined && wrong > baseline.wrongLines) {
reasons.push(`Wrong-line answers rose from ${baseline.wrongLines} to ${wrong}`);
}
const nowOnMethod = new Set(suite.rows.filter((row) => row.onMethod).map((row) => row.id));
const regressions = (baseline?.onMethod ?? []).filter((id) => !nowOnMethod.has(id));
return { publish: reasons.length === 0, reasons, regressions, wrongLines: wrong };
}pnpm eval runs this and exits non-zero when the gate fails. On Replit, it goes in the [deployment] build command, so a failing score fails the build and nothing is published. See the 30-question test.
Monitoring
Each answer is logged with its path (answer bank, retrieval, no match), outcome, wait and attempts. A question is unanswered if the rep got an error or was told to try again; the error rate is unanswered questions over questions asked, in 15-minute windows. Alerts fire on three unanswered questions within five minutes, an error rate above 5%, slow answers, and (as information) each time the verbatim check had to restore a line.
Show the code: the error rate
/**
* A question is unanswered if the rep never got an answer: a hard failure, or a
* "try again" message. Both count toward the error rate and the alerts.
*/
export function bucketize(runs: RunRecord[], bucketMinutes = BUCKET_MINUTES, dayMinutes = DAY_MINUTES): Bucket[] {
const buckets: Bucket[] = [];
for (let start = 0; start < dayMinutes; start += bucketMinutes) {
const inside = runs.filter((run) => run.minute >= start && run.minute < start + bucketMinutes);
const failed = inside.filter((run) => run.outcome === "failed").length;
const busy = inside.filter((run) => run.outcome === "busy-retry").length;
buckets.push({
start,
requests: inside.length,
failed,
busy,
unanswered: failed + busy,
errorRate: inside.length ? (failed + busy) / inside.length : 0,
p95Ms: p95(inside.filter((run) => !unanswered(run)).map((run) => run.latencyMs)),
});
}
return buckets;
}Running against a real model
The clients take any fetch-compatible transport. The demo plugs in the simulated provider; with OPENAI_API_KEY set, pnpm smoke:openai sends one question through the same resilient client to the real API. OPENAI_BASE_URL points it at another OpenAI-compatible endpoint, such as the one Replit's AI integration provides. The deployed demo has no key and makes no real model calls.
Show the code: the real-API transport
/**
* The real API plugs into the same clients as the simulated provider: both are
* a fetch-compatible transport. Not used in the deployed demo (no key is set).
*/
export function openAITransport(apiKey: string): Transport {
return (url, init) =>
fetch(url, {
method: init.method,
body: init.body,
signal: init.signal,
headers: { ...init.headers, authorization: `Bearer ${apiKey}` },
});
}