@convex-dev/ai-budget 0.0.2-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,196 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `ComponentApi` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type { FunctionReference } from "convex/server";
12
+
13
+ /**
14
+ * A utility for referencing a Convex component's exposed API.
15
+ *
16
+ * Useful when expecting a parameter like `components.myComponent`.
17
+ * Usage:
18
+ * ```ts
19
+ * async function myFunction(ctx: QueryCtx, component: ComponentApi) {
20
+ * return ctx.runQuery(component.someFile.someQuery, { ...args });
21
+ * }
22
+ * ```
23
+ */
24
+ export type ComponentApi<Name extends string | undefined = string | undefined> =
25
+ {
26
+ lib: {
27
+ bumpAction: FunctionReference<
28
+ "mutation",
29
+ "internal",
30
+ { dailyNanos?: number; lifetimeNanos?: number; name: string },
31
+ null,
32
+ Name
33
+ >;
34
+ bumpGlobal: FunctionReference<
35
+ "mutation",
36
+ "internal",
37
+ { dailyNanos?: number; lifetimeNanos?: number },
38
+ null,
39
+ Name
40
+ >;
41
+ bumpUser: FunctionReference<
42
+ "mutation",
43
+ "internal",
44
+ { dailyNanos?: number; lifetimeNanos?: number; userId: string },
45
+ null,
46
+ Name
47
+ >;
48
+ deleteUser: FunctionReference<
49
+ "mutation",
50
+ "internal",
51
+ { userId: string },
52
+ { deletedThisBatch: number; done: boolean },
53
+ Name
54
+ >;
55
+ finishRequest: FunctionReference<
56
+ "mutation",
57
+ "internal",
58
+ {
59
+ cachedTokens?: number;
60
+ completionTokens?: number;
61
+ error?: string;
62
+ latencyMs?: number;
63
+ promptTokens?: number;
64
+ requestId: string;
65
+ responseText?: string;
66
+ },
67
+ { costNanos: number },
68
+ Name
69
+ >;
70
+ getGlobalStatus: FunctionReference<
71
+ "query",
72
+ "internal",
73
+ {},
74
+ {
75
+ dailySpendLimitNanos: number | null;
76
+ enforcement: "hard" | "soft";
77
+ lifetimeSpendLimitNanos: number | null;
78
+ spentTodayNanos: number;
79
+ spentTotalNanos: number;
80
+ },
81
+ Name
82
+ >;
83
+ getModelPolicy: FunctionReference<
84
+ "query",
85
+ "internal",
86
+ {},
87
+ { mode: "open" | "allowlist" | "denylist"; models: Array<string> },
88
+ Name
89
+ >;
90
+ getRequest: FunctionReference<
91
+ "query",
92
+ "internal",
93
+ { requestId: string },
94
+ any,
95
+ Name
96
+ >;
97
+ lineage: FunctionReference<
98
+ "query",
99
+ "internal",
100
+ { requestId: string },
101
+ any,
102
+ Name
103
+ >;
104
+ listActions: FunctionReference<"query", "internal", {}, any, Name>;
105
+ listPrices: FunctionReference<"query", "internal", {}, any, Name>;
106
+ listRequests: FunctionReference<
107
+ "query",
108
+ "internal",
109
+ { limit?: number; userId?: string },
110
+ any,
111
+ Name
112
+ >;
113
+ listUsers: FunctionReference<"query", "internal", {}, any, Name>;
114
+ setActionLimits: FunctionReference<
115
+ "mutation",
116
+ "internal",
117
+ {
118
+ dailySpendLimitNanos?: number;
119
+ dailyTokenLimit?: number;
120
+ disabled?: boolean;
121
+ enforcement?: "hard" | "soft";
122
+ lifetimeSpendLimitNanos?: number;
123
+ lifetimeTokenLimit?: number;
124
+ name: string;
125
+ },
126
+ null,
127
+ Name
128
+ >;
129
+ setGlobalLimits: FunctionReference<
130
+ "mutation",
131
+ "internal",
132
+ {
133
+ dailySpendLimitNanos?: number;
134
+ enforcement?: "hard" | "soft";
135
+ lifetimeSpendLimitNanos?: number;
136
+ },
137
+ null,
138
+ Name
139
+ >;
140
+ setLimits: FunctionReference<
141
+ "mutation",
142
+ "internal",
143
+ {
144
+ blocked?: boolean;
145
+ dailySpendLimitNanos?: number;
146
+ dailyTokenLimit?: number;
147
+ enforcement?: "hard" | "soft";
148
+ lifetimeSpendLimitNanos?: number;
149
+ lifetimeTokenLimit?: number;
150
+ requestsPerMinute?: number;
151
+ userId: string;
152
+ },
153
+ null,
154
+ Name
155
+ >;
156
+ setModelPolicy: FunctionReference<
157
+ "mutation",
158
+ "internal",
159
+ { mode: "open" | "allowlist" | "denylist"; models: Array<string> },
160
+ null,
161
+ Name
162
+ >;
163
+ setPrice: FunctionReference<
164
+ "mutation",
165
+ "internal",
166
+ {
167
+ inputNanosPerMTok: number;
168
+ model: string;
169
+ outputNanosPerMTok: number;
170
+ },
171
+ null,
172
+ Name
173
+ >;
174
+ setRetention: FunctionReference<
175
+ "mutation",
176
+ "internal",
177
+ { retentionMs: number },
178
+ null,
179
+ Name
180
+ >;
181
+ startRequest: FunctionReference<
182
+ "mutation",
183
+ "internal",
184
+ {
185
+ actionName?: string;
186
+ messages: Array<{ content: string; role: string }>;
187
+ model: string;
188
+ rerunOf?: string;
189
+ userId: string;
190
+ },
191
+ | { allowed: true; requestId: string; warnings: Array<string> }
192
+ | { allowed: false; code: string; reason: string },
193
+ Name
194
+ >;
195
+ };
196
+ };
@@ -0,0 +1,60 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ DataModelFromSchemaDefinition,
13
+ DocumentByName,
14
+ TableNamesInDataModel,
15
+ SystemTableNames,
16
+ } from "convex/server";
17
+ import type { GenericId } from "convex/values";
18
+ import schema from "../schema.js";
19
+
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
23
+ export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
30
+ export type Doc<TableName extends TableNames> = DocumentByName<
31
+ DataModel,
32
+ TableName
33
+ >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
48
+ export type Id<TableName extends TableNames | SystemTableNames> =
49
+ GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
60
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -0,0 +1,169 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ ActionBuilder,
13
+ HttpActionBuilder,
14
+ MutationBuilder,
15
+ QueryBuilder,
16
+ GenericActionCtx,
17
+ GenericMutationCtx,
18
+ GenericQueryCtx,
19
+ GenericDatabaseReader,
20
+ GenericDatabaseWriter,
21
+ } from "convex/server";
22
+ import {
23
+ actionGeneric,
24
+ httpActionGeneric,
25
+ queryGeneric,
26
+ mutationGeneric,
27
+ internalActionGeneric,
28
+ internalMutationGeneric,
29
+ internalQueryGeneric,
30
+ } from "convex/server";
31
+ import type { DataModel } from "./dataModel.js";
32
+
33
+ /**
34
+ * Typesafe environment variables.
35
+ *
36
+ * This includes platform-provided env vars and any variables declared in
37
+ * `convex.config.ts`.
38
+ */
39
+ type Env = {
40
+ readonly CONVEX_CLOUD_URL: string;
41
+ readonly CONVEX_SITE_URL: string;
42
+ };
43
+
44
+ /**
45
+ * Define a query in this Convex app's public API.
46
+ *
47
+ * This function will be allowed to read your Convex database and will be accessible from the client.
48
+ *
49
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
50
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
51
+ */
52
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
53
+
54
+ /**
55
+ * Define a query that is only accessible from other Convex functions (but not from the client).
56
+ *
57
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
58
+ *
59
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
60
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
63
+ internalQueryGeneric;
64
+
65
+ /**
66
+ * Define a mutation in this Convex app's public API.
67
+ *
68
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
69
+ *
70
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
71
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
72
+ */
73
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
74
+
75
+ /**
76
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
77
+ *
78
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
79
+ *
80
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
81
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
82
+ */
83
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
84
+ internalMutationGeneric;
85
+
86
+ /**
87
+ * Define an action in this Convex app's public API.
88
+ *
89
+ * An action is a function which can execute any JavaScript code, including non-deterministic
90
+ * code and code with side-effects, like calling third-party services.
91
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
92
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
93
+ *
94
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
95
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
96
+ */
97
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
98
+
99
+ /**
100
+ * Define an action that is only accessible from other Convex functions (but not from the client).
101
+ *
102
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
103
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
104
+ */
105
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
106
+ internalActionGeneric;
107
+
108
+ /**
109
+ * Define an HTTP action.
110
+ *
111
+ * The wrapped function will be used to respond to HTTP requests received
112
+ * by a Convex deployment if the requests matches the path and method where
113
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
114
+ *
115
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
116
+ * and a Fetch API `Request` object as its second.
117
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
118
+ */
119
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
120
+ export const env: Env = (globalThis as unknown as { process: { env: Env } })
121
+ .process.env;
122
+
123
+ /**
124
+ * A set of services for use within Convex query functions.
125
+ *
126
+ * The query context is passed as the first argument to any Convex query
127
+ * function run on the server.
128
+ *
129
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
130
+ */
131
+ export type QueryCtx = GenericQueryCtx<DataModel>;
132
+
133
+ /**
134
+ * A set of services for use within Convex mutation functions.
135
+ *
136
+ * The mutation context is passed as the first argument to any Convex mutation
137
+ * function run on the server.
138
+ *
139
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
140
+ */
141
+ export type MutationCtx = GenericMutationCtx<DataModel>;
142
+
143
+ /**
144
+ * A set of services for use within Convex action functions.
145
+ *
146
+ * The action context is passed as the first argument to any Convex action
147
+ * function run on the server.
148
+ */
149
+ export type ActionCtx = GenericActionCtx<DataModel>;
150
+
151
+ /**
152
+ * An interface to read from the database within Convex query functions.
153
+ *
154
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
155
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
156
+ * building a query.
157
+ */
158
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
159
+
160
+ /**
161
+ * An interface to read from and write to the database within Convex mutation
162
+ * functions.
163
+ *
164
+ * Convex guarantees that all writes within a single mutation are
165
+ * executed atomically, so you never have to worry about partial writes leaving
166
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
167
+ * for the guarantees Convex provides your functions.
168
+ */
169
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,7 @@
1
+ import { defineComponent } from "convex/server";
2
+ import shardedCounter from "@convex-dev/sharded-counter/convex.config";
3
+
4
+ const component = defineComponent("aiBudget");
5
+ // Global spend totals use a sharded counter for high write throughput.
6
+ component.use(shardedCounter);
7
+ export default component;
@@ -0,0 +1,15 @@
1
+ import { cronJobs } from "convex/server";
2
+ import { internal } from "./_generated/api";
3
+
4
+ const crons = cronJobs();
5
+
6
+ // Backstop reservation/settlement: fold any finished-but-unfolded requests and
7
+ // release reservations for requests that never settled.
8
+ crons.interval(
9
+ "reconcile ai gateway spend",
10
+ { minutes: 1 },
11
+ internal.lib.reconcile,
12
+ {}
13
+ );
14
+
15
+ export default crons;
@@ -0,0 +1,151 @@
1
+ import { convexTest } from "convex-test";
2
+ import { describe, expect, test, vi } from "vitest";
3
+ import schema from "./schema";
4
+ import { api } from "./_generated/api";
5
+
6
+ // convex-test loads the component's own modules; exclude convex.config (not a
7
+ // function module) and the test files themselves.
8
+ const modules = import.meta.glob([
9
+ "./**/*.ts",
10
+ "!./**/*.test.ts",
11
+ "!./**/convex.config.ts",
12
+ ]);
13
+
14
+ const MODEL = "openai/gpt-4o-mini";
15
+ const msg = (content: string) => [{ role: "user", content }];
16
+
17
+ async function start(t: any, args: any) {
18
+ return t.mutation(api.lib.startRequest, {
19
+ model: MODEL,
20
+ messages: msg("hi"),
21
+ ...args,
22
+ });
23
+ }
24
+ async function settle(t: any, requestId: any, p = 10, c = 5) {
25
+ await t.mutation(api.lib.finishRequest, {
26
+ requestId,
27
+ promptTokens: p,
28
+ completionTokens: c,
29
+ });
30
+ // finishRequest schedules the fold via runAfter(0); drain it.
31
+ vi.useFakeTimers();
32
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
33
+ vi.useRealTimers();
34
+ }
35
+ const userOf = async (t: any, userId: string) =>
36
+ (await t.query(api.lib.listUsers, {})).find((u: any) => u.userId === userId);
37
+
38
+ describe("reserve / settle spend caps", () => {
39
+ test("a daily cap below one request's reservation blocks up front", async () => {
40
+ const t = convexTest(schema, modules);
41
+ // one gpt-4o-mini request reserves ~480_000 nanodollars ($0.00048); a
42
+ // 1_000-nano ($0.000001) cap can't fit it.
43
+ await t.mutation(api.lib.setLimits, {
44
+ userId: "u",
45
+ dailySpendLimitNanos: 1_000,
46
+ });
47
+ const r = await start(t, { userId: "u" });
48
+ expect(r.allowed).toBe(false);
49
+ expect(r.code).toBe("user_daily_spend_limit");
50
+ });
51
+
52
+ test("reservation is released and settled to the real cost", async () => {
53
+ const t = convexTest(schema, modules);
54
+ await t.mutation(api.lib.setLimits, {
55
+ userId: "u",
56
+ dailySpendLimitNanos: 1_000_000_000, // $1/day
57
+ });
58
+ const r = await start(t, { userId: "u" });
59
+ expect(r.allowed).toBe(true);
60
+ await settle(t, r.requestId, 1_000_000, 1_000_000); // 1M in, 1M out
61
+ const u = await userOf(t, "u");
62
+ // gpt-4o-mini: $0.15/Mtok in + $0.60/Mtok out = $0.75 = 750_000_000 nano.
63
+ expect(u.totalSpendNanos).toBe(750_000_000);
64
+ expect(u.reservedTotalNanos ?? 0).toBe(0);
65
+ expect(u.pendingCount ?? 0).toBe(0);
66
+ expect(u.totalRequests).toBe(1);
67
+ });
68
+ });
69
+
70
+ describe("D-00 exactly-once settlement", () => {
71
+ test("a duplicate finishRequest does not double-count", async () => {
72
+ const t = convexTest(schema, modules);
73
+ const r = await start(t, { userId: "u" });
74
+ await settle(t, r.requestId); // first settle
75
+ const before = await userOf(t, "u");
76
+ await settle(t, r.requestId); // late duplicate — must be a no-op
77
+ const after = await userOf(t, "u");
78
+ expect(after.totalRequests).toBe(1);
79
+ expect(after.totalRequests).toBe(before.totalRequests);
80
+ expect(after.totalSpendNanos).toBeCloseTo(before.totalSpendNanos, 9);
81
+ expect(after.reservedTotalNanos ?? 0).toBeCloseTo(0, 9);
82
+ });
83
+ });
84
+
85
+ describe("token quotas", () => {
86
+ test("a tiny daily token cap blocks (estimate exceeds it)", async () => {
87
+ const t = convexTest(schema, modules);
88
+ await t.mutation(api.lib.setLimits, { userId: "u", dailyTokenLimit: 10 });
89
+ const r = await start(t, { userId: "u" });
90
+ expect(r.allowed).toBe(false);
91
+ expect(r.code).toBe("user_daily_token_limit");
92
+ });
93
+ });
94
+
95
+ describe("soft enforcement", () => {
96
+ test("over a soft budget: allowed, warned, flagged overBudget", async () => {
97
+ const t = convexTest(schema, modules);
98
+ await t.mutation(api.lib.setLimits, {
99
+ userId: "u",
100
+ dailySpendLimitNanos: 1, // 1 nanodollar — one estimate blows past it
101
+ enforcement: "soft",
102
+ });
103
+ const r = await start(t, { userId: "u" });
104
+ expect(r.allowed).toBe(true);
105
+ expect(r.warnings.length).toBeGreaterThan(0);
106
+ const req = await t.query(api.lib.getRequest, { requestId: r.requestId });
107
+ expect(req.overBudget).toBe(true);
108
+ });
109
+ });
110
+
111
+ describe("model policy", () => {
112
+ test("allowlist blocks an off-list model", async () => {
113
+ const t = convexTest(schema, modules);
114
+ await t.mutation(api.lib.setModelPolicy, {
115
+ mode: "allowlist",
116
+ models: ["openai/gpt-4o-mini"],
117
+ });
118
+ const blocked = await start(t, { userId: "u", model: "openai/gpt-4o" });
119
+ expect(blocked.allowed).toBe(false);
120
+ expect(blocked.code).toBe("model_not_allowed");
121
+ const ok = await start(t, { userId: "u", model: "openai/gpt-4o-mini" });
122
+ expect(ok.allowed).toBe(true);
123
+ });
124
+ });
125
+
126
+ describe("D-02 pricing validation", () => {
127
+ test("setPrice rejects negative rates", async () => {
128
+ const t = convexTest(schema, modules);
129
+ await expect(
130
+ t.mutation(api.lib.setPrice, {
131
+ model: "x/y",
132
+ inputNanosPerMTok: -1,
133
+ outputNanosPerMTok: 5,
134
+ })
135
+ ).rejects.toThrow(/non-negative/);
136
+ });
137
+ });
138
+
139
+ describe("F-04 fail-closed pricing", () => {
140
+ test("an unknown model is charged the conservative max, not zero", async () => {
141
+ const t = convexTest(schema, modules);
142
+ const r = await start(t, { userId: "u", model: "made/up-model" });
143
+ expect(r.allowed).toBe(true);
144
+ await settle(t, r.requestId, 1_000_000, 1_000_000);
145
+ const u = await userOf(t, "u");
146
+ // conservative = max over table = {$3 in, $15 out}/Mtok => $18 = 18e9 nano.
147
+ expect(u.totalSpendNanos).toBe(18_000_000_000);
148
+ const req = await t.query(api.lib.getRequest, { requestId: r.requestId });
149
+ expect(req.unpricedModel).toBe(true);
150
+ });
151
+ });