Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- CreateTable
CREATE TABLE "PlatformAiCall" (
"id" TEXT NOT NULL,
"feature" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"inputTokens" INTEGER NOT NULL DEFAULT 0,
"outputTokens" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "PlatformAiCall_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "PlatformAiCall_feature_createdAt_idx" ON "PlatformAiCall"("feature", "createdAt");

-- CreateIndex
CREATE INDEX "PlatformAiCall_userId_feature_createdAt_idx" ON "PlatformAiCall"("userId", "feature", "createdAt");

-- AddForeignKey
ALTER TABLE "PlatformAiCall" ADD CONSTRAINT "PlatformAiCall_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
17 changes: 17 additions & 0 deletions server/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,7 @@ model User {
aiCredential AiCredential?
aiInterviewSessions AiInterviewSession[]
learnerQuestions LearnerQuestion[]
platformAiCalls PlatformAiCall[]
personalizedPrompts PersonalizedPrompt[]
capstoneChecks CapstoneCheck[]
shellLabProgress ShellLabProgress[]
Expand Down Expand Up @@ -1878,6 +1879,22 @@ model LearnerQuestion {
@@index([userId, createdAt])
}

/// One model call paid for with the platform's own AI key (short-answer grading without a
/// learner key, suggested help replies). Reserved before the call so daily caps hold across
/// replicas; released only when the provider did not bill the call.
model PlatformAiCall {
id String @id @default(cuid())
feature String
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
inputTokens Int @default(0)
outputTokens Int @default(0)
createdAt DateTime @default(now())

@@index([feature, createdAt])
@@index([userId, feature, createdAt])
}

/// A learner's own wording of an open question that opted into `personalize`, written by
/// the model from their earlier answers. One row per learner and block; it stays put once
/// the learner has answered, so the question they see never changes under them.
Expand Down
9 changes: 9 additions & 0 deletions server/src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,15 @@ const schema = z.object({
HELP_REPLY_MODEL: z.string().trim().min(1).default("claude-sonnet-5-5"),
/** Drafts the whole platform may make per UTC day, the cap on the Anthropic bill. */
AI_REVIEW_DAILY_LIMIT: z.coerce.number().int().min(1).max(20_000).default(1_000),
/**
* Short answers graded on the platform's key (learners without their own key). Counted in
* the PlatformAiCall table before the model is called, so they hold across restarts and replicas.
*/
SHORT_ANSWER_PLATFORM_DAILY_LIMIT: z.coerce.number().int().min(1).max(1_000).default(40),
SHORT_ANSWER_PLATFORM_GLOBAL_DAILY_LIMIT: z.coerce.number().int().min(1).max(200_000).default(3_000),
/** Suggested help replies one mentor may ask for per UTC day, and the whole platform. */
HELP_REPLY_DRAFT_DAILY_LIMIT: z.coerce.number().int().min(1).max(2_000).default(60),
HELP_REPLY_DRAFT_GLOBAL_DAILY_LIMIT: z.coerce.number().int().min(1).max(50_000).default(500),
/** Optional fine-grained GitHub token, public read only. Without it the API allows 60 calls an hour, about 12 checks. */
GITHUB_TOKEN: optionalString,
/** Edorax's LinkedIn company id for Add to profile; without it LinkedIn gets the name "Edorax" as text. */
Expand Down
5 changes: 5 additions & 0 deletions server/src/services/ai/chapter-qa/practice-quiz.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,7 @@ export async function generatePracticeQuiz(
messages: [{ role: "user", content: userPrompt }],
});

keepReservation = true;
await recordTokens(reservation, {
inputTokens: message.usage.input_tokens,
outputTokens: message.usage.output_tokens,
Expand Down Expand Up @@ -374,8 +375,12 @@ export async function generatePracticeQuiz(
},
fetchImpl: deps.fetchImpl,
});
keepReservation = true;
}

// From here the provider has answered and billed the call, so the quiz stays counted even if
// the answer cannot be used. Otherwise a crafted `focus` that breaks the JSON would give
// unlimited free generations.
let parsedJson: unknown;
try {
parsedJson = parseModelJson(rawText);
Expand Down
13 changes: 11 additions & 2 deletions server/src/services/ai/chapter-qa/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,17 @@ function failure(error: unknown, chapterId: string): AppError {

export async function askAboutChapter(input: AskInput, deps: ChapterQaDeps = {}): Promise<ChapterQuestionAnswer> {
const prepared = await prepareQuestion(input);
// Once the provider has answered, the call is paid for: the question stays counted even if
// the answer is unusable, so nobody gets free calls by making answers fail.
let billed = false;
try {
const provider = resolveQaProvider(deps.client);
if (!provider) throw new AppError(NOT_AVAILABLE, 503, "QA_UNAVAILABLE");

let answer: string;
if (provider.kind === "anthropic") {
const message = await provider.client.messages.create(prepared.params);
billed = true;
await recordTokens(prepared.reservation, { inputTokens: message.usage.input_tokens, outputTokens: message.usage.output_tokens });
const text = message.content
.flatMap((block) => (block.type === "text" ? [block.text] : []))
Expand All @@ -156,12 +160,13 @@ export async function askAboutChapter(input: AskInput, deps: ChapterQaDeps = {})
temperature: 0.3,
fetchImpl: deps.fetchImpl,
});
billed = true;
}

if (!answer) throw new AppError(TRY_LATER, 502, "QA_FAILED");
return { answer, ...(await remainingToday(prepared.learnerId)) };
} catch (error) {
await releaseQuestion(prepared.reservation).catch(() => undefined);
if (!billed) await releaseQuestion(prepared.reservation).catch(() => undefined);
throw failure(error, prepared.chapterId);
}
}
Expand All @@ -184,6 +189,7 @@ export async function streamAnswerAboutChapter(input: AskInput, deps: ChapterQaD
const prepared = await prepareQuestion(input);
const run = async (write: (chunk: string) => void) => {
let wrote = false;
let billed = false;
try {
const provider = resolveQaProvider(deps.client);
if (!provider) throw new AppError(NOT_AVAILABLE, 503, "QA_UNAVAILABLE");
Expand All @@ -196,6 +202,7 @@ export async function streamAnswerAboutChapter(input: AskInput, deps: ChapterQaD
write(delta);
});
const message = await stream.finalMessage();
billed = true;
await recordTokens(prepared.reservation, { inputTokens: message.usage.input_tokens, outputTokens: message.usage.output_tokens });
if (message.stop_reason === "refusal" && !wrote) write(DECLINED);
else if (!wrote) throw new AppError(TRY_LATER, 502, "QA_FAILED");
Expand All @@ -209,12 +216,14 @@ export async function streamAnswerAboutChapter(input: AskInput, deps: ChapterQaD
temperature: 0.3,
fetchImpl: deps.fetchImpl,
});
billed = true;
if (!answer.trim()) throw new AppError(TRY_LATER, 502, "QA_FAILED");
wrote = true;
write(answer);
}
} catch (error) {
await releaseQuestion(prepared.reservation).catch(() => undefined);
// Text already streamed means the provider was generating, and billing, this answer.
if (!billed && !wrote) await releaseQuestion(prepared.reservation).catch(() => undefined);
write(STREAM_ERROR_MARK + failure(error, prepared.chapterId).message);
}
};
Expand Down
64 changes: 64 additions & 0 deletions server/src/services/ai/platform-usage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { prisma } from "../../db/prisma.js";
import { AppError, TooManyRequestsError } from "../../utils/errors.js";
import { startOfUtcDay } from "./chapter-qa/usage.js";

// Daily caps for model calls paid with the platform's own key. A row is reserved under a
// lock before the model is called, so parallel requests cannot all pass the check at once,
// and the caps hold across restarts and replicas. A row is released only when the provider
// refused the call before doing any work; a call that got an answer (even one we could not
// use) stays counted, so nobody can get free calls by making the answer fail.

export type PlatformFeature = "short-answer" | "help-reply";

export type PlatformLimits = {
perUserDaily: number;
globalDaily: number;
/** Calls one user may start in any 60 seconds. */
perMinute?: number;
/** What the user sees at their own daily cap. */
userMessage: string;
/** What the user sees when the platform-wide cap is reached. */
globalMessage: string;
};

const MINUTE_MS = 60_000;

export async function reservePlatformCall(
input: { userId: string; feature: PlatformFeature; limits: PlatformLimits },
now = new Date()
): Promise<string> {
const { userId, feature, limits } = input;
return prisma.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`platform-ai:${feature}`}))`;
const dayStart = startOfUtcDay(now);
const today = await tx.platformAiCall.count({ where: { feature, createdAt: { gte: dayStart } } });
if (today >= limits.globalDaily) throw new AppError(limits.globalMessage, 503, "AI_DAILY_CAP");
const perUser = await tx.platformAiCall.count({ where: { userId, feature, createdAt: { gte: dayStart } } });
if (perUser >= limits.perUserDaily) throw new TooManyRequestsError(limits.userMessage);
if (limits.perMinute) {
const lastMinute = await tx.platformAiCall.count({
where: { userId, feature, createdAt: { gte: new Date(now.getTime() - MINUTE_MS) } },
});
if (lastMinute >= limits.perMinute) throw new TooManyRequestsError("You are going quickly. Wait a minute and try again.");
}
const row = await tx.platformAiCall.create({ data: { userId, feature }, select: { id: true } });
return row.id;
});
}

export async function recordPlatformTokens(id: string, usage: { inputTokens: number; outputTokens: number }): Promise<void> {
await prisma.platformAiCall.update({ where: { id }, data: usage }).catch(() => undefined);
}

/** Give the call back. Use only when the provider did not bill it (see providerDidNotBill). */
export async function releasePlatformCall(id: string): Promise<void> {
await prisma.platformAiCall.deleteMany({ where: { id } });
}

/** Codes where the provider rejected the request before generating anything. */
const NOT_BILLED = new Set(["AI_NOT_CONFIGURED", "AI_KEY_INVALID", "AI_OUT_OF_CREDIT", "AI_RATE_LIMITED", "AI_MODEL_UNAVAILABLE"]);

export function providerDidNotBill(error: unknown): boolean {
const code = (error as { code?: unknown } | null)?.code;
return typeof code === "string" && NOT_BILLED.has(code);
}
58 changes: 43 additions & 15 deletions server/src/services/ai/short-answer/grade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { DEFAULT_HINT_AFTER_ATTEMPTS } from "../../../shared/blocks/open-questio
import { env, shortAnswerPlatformKeyAvailable } from "../../../config/env.js";
import { loadAiKeyForUse } from "../credentials.js";
import { AiError, createChatCompletion, type AiProviderName } from "../openrouter.js";
import { providerDidNotBill, recordPlatformTokens, releasePlatformCall, reservePlatformCall } from "../platform-usage.js";

// Instant short-answer grading with the learner's OpenRouter key. The model
// only decides correct/incorrect and a short "why"; authored hints are chosen
Expand Down Expand Up @@ -114,6 +115,7 @@ async function callModel(input: {
sampleAnswer?: string;
rubric?: string;
fetchImpl?: typeof fetch;
onUsage?: (usage: { inputTokens: number; outputTokens: number }) => void;
}): Promise<{ correct: boolean; why: string; guidance: string }> {
const content = await createChatCompletion({
apiKey: input.apiKey,
Expand All @@ -132,6 +134,7 @@ async function callModel(input: {
responseFormat: { type: "json_schema", json_schema: gradeJsonSchema },
timeoutMs: 30_000,
fetchImpl: input.fetchImpl,
onUsage: input.onUsage,
});

let parsedJson: unknown;
Expand All @@ -152,12 +155,12 @@ async function callModel(input: {
async function loadKeyOrPlatform(
userId: string,
deps: Deps
): Promise<{ provider: AiProviderName; apiKey: string; model: string }> {
): Promise<{ provider: AiProviderName; apiKey: string; model: string; platform: boolean }> {
try {
return await loadAiKeyForUse(userId, deps);
return { ...(await loadAiKeyForUse(userId, deps)), platform: false };
} catch (error) {
if (error instanceof AiError && error.code === "AI_KEY_REQUIRED" && shortAnswerPlatformKeyAvailable) {
return { provider: "ANTHROPIC", apiKey: env.ANTHROPIC_API_KEY!, model: env.AI_REVIEW_MODEL };
return { provider: "ANTHROPIC", apiKey: env.ANTHROPIC_API_KEY!, model: env.AI_REVIEW_MODEL, platform: true };
}
throw error;
}
Expand All @@ -182,20 +185,45 @@ export async function gradeShortAnswerWithLlm(input: {
);
}

const { provider, apiKey, model } =
const { provider, apiKey, model, platform } =
deps.apiKey && deps.model
? { provider: "OPENROUTER" as const, apiKey: deps.apiKey, model: deps.model }
? { provider: "OPENROUTER" as const, apiKey: deps.apiKey, model: deps.model, platform: false }
: await loadKeyOrPlatform(userId, deps);
const gradeFn = deps.gradeFn ?? ((args) => callModel({ ...args, fetchImpl: deps.fetchImpl }));
const graded = await gradeFn({
apiKey,
provider,
model,
prompt: config.prompt,
answer,
sampleAnswer: config.sampleAnswer,
rubric: config.rubric,
});

// On the platform's key every call is counted before it is made: per learner, per minute and
// platform-wide. A learner's own key is their own bill, so it is not capped here.
const reservation = platform
? await reservePlatformCall({
userId,
feature: "short-answer",
limits: {
perUserDaily: env.SHORT_ANSWER_PLATFORM_DAILY_LIMIT,
globalDaily: env.SHORT_ANSWER_PLATFORM_GLOBAL_DAILY_LIMIT,
perMinute: 6,
userMessage: `You have used today's ${env.SHORT_ANSWER_PLATFORM_DAILY_LIMIT} instant checks. Add your own AI key in settings for more, or try again tomorrow.`,
globalMessage: "Instant feedback is paused for today. Please try again tomorrow, or add your own AI key in settings.",
},
})
: null;
const usage: { value: { inputTokens: number; outputTokens: number } | null } = { value: null };
const gradeFn = deps.gradeFn ?? ((args) => callModel({ ...args, fetchImpl: deps.fetchImpl, onUsage: (value) => { usage.value = value; } }));
let graded: Awaited<ReturnType<NonNullable<Deps["gradeFn"]>>>;
try {
graded = await gradeFn({
apiKey,
provider,
model,
prompt: config.prompt,
answer,
sampleAnswer: config.sampleAnswer,
rubric: config.rubric,
});
} catch (error) {
if (reservation && providerDidNotBill(error)) await releasePlatformCall(reservation).catch(() => undefined);
throw error;
} finally {
if (reservation && usage.value) await recordPlatformTokens(reservation, usage.value);
}

const why = graded.why.slice(0, 800);
if (graded.correct) {
Expand Down
8 changes: 8 additions & 0 deletions server/src/services/blocks/respond.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ export type BlockResponseResult = {

type Graded = GradeResult & Omit<BlockResponseResult, keyof GradeResult>;

/** Longest open answer accepted. About 4,000 words: far past any real answer, small for a model bill. */
export const OPEN_ANSWER_MAX_CHARS = 20_000;

/** Parse the payload with the block's own schema and grade it — pure, no I/O. */
function gradeBlock(type: string, config: unknown, payload: unknown): Graded {
switch (type) {
Expand Down Expand Up @@ -150,6 +153,11 @@ export async function submitBlockResponse(input: {
}
});

// Open answers go to AI grading and AI review drafts, so a huge paste would be a huge bill.
if (block.type === "OPEN_QUESTION" && typeof payload.text === "string" && payload.text.length > OPEN_ANSWER_MAX_CHARS) {
throw new BadRequestError(`Keep your answer under ${OPEN_ANSWER_MAX_CHARS.toLocaleString("en-US")} characters.`, "ANSWER_TOO_LONG");
}

const previousAttempts = await prisma.response.count({ where: { blockId, userId: learner.id } });
const attempt = previousAttempts + 1;

Expand Down
10 changes: 8 additions & 2 deletions server/src/services/teach/ai/auto-draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ export async function loadReviewDraftContext(responseId: string): Promise<Review
take: 3,
select: { review: { select: { feedback: true } } },
});
const answerParts = [payload.data.text.trim()];
// Capped like a new submission (blocks/respond.ts), so an older or imported huge answer stays cheap.
const answerParts = [payload.data.text.trim().slice(0, 20_000)];
if (payload.data.url?.trim()) answerParts.push(`Submitted URL (not fetched): ${payload.data.url.trim()}`);

return {
Expand All @@ -72,7 +73,12 @@ export async function loadReviewDraftContext(responseId: string): Promise<Review
}

async function underDailyCap(now = new Date()): Promise<boolean> {
const used = await prisma.response.count({ where: { aiDraftAt: { gte: startOfUtcDay(now) } } });
// Failed tries count too: most of them reached the model and were billed, and "Try again"
// must not become a way around the cap.
const dayStart = startOfUtcDay(now);
const used = await prisma.response.count({
where: { OR: [{ aiDraftAt: { gte: dayStart } }, { aiDraftFailedAt: { gte: dayStart } }] },
});
return used < env.AI_REVIEW_DAILY_LIMIT;
}

Expand Down
Loading
Loading