graphile-llm 0.7.2 → 0.8.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.
- package/__tests__/graphile-llm.test.js +6 -4
- package/chat.d.ts +5 -5
- package/chat.js +8 -16
- package/config-cache.d.ts +77 -0
- package/config-cache.js +148 -0
- package/embedder.d.ts +5 -5
- package/embedder.js +8 -16
- package/env.d.ts +31 -0
- package/env.js +52 -0
- package/esm/__tests__/graphile-llm.test.js +6 -4
- package/esm/chat.d.ts +5 -5
- package/esm/chat.js +8 -16
- package/esm/config-cache.d.ts +77 -0
- package/esm/config-cache.js +143 -0
- package/esm/embedder.d.ts +5 -5
- package/esm/embedder.js +8 -16
- package/esm/env.d.ts +31 -0
- package/esm/env.js +49 -0
- package/esm/index.d.ts +10 -1
- package/esm/index.js +11 -1
- package/esm/metering.d.ts +114 -0
- package/esm/metering.js +358 -0
- package/esm/plugins/agent-discovery-plugin.d.ts +29 -0
- package/esm/plugins/agent-discovery-plugin.js +65 -0
- package/esm/plugins/llm-module-plugin.d.ts +10 -1
- package/esm/plugins/llm-module-plugin.js +11 -3
- package/esm/plugins/metering-plugin.d.ts +42 -0
- package/esm/plugins/metering-plugin.js +175 -0
- package/esm/plugins/text-mutation-plugin.d.ts +4 -0
- package/esm/plugins/text-mutation-plugin.js +11 -1
- package/esm/plugins/text-search-plugin.d.ts +4 -0
- package/esm/plugins/text-search-plugin.js +13 -1
- package/esm/preset.d.ts +21 -1
- package/esm/preset.js +29 -2
- package/esm/types.d.ts +47 -6
- package/index.d.ts +10 -1
- package/index.js +23 -2
- package/metering.d.ts +114 -0
- package/metering.js +365 -0
- package/package.json +15 -15
- package/plugins/agent-discovery-plugin.d.ts +29 -0
- package/plugins/agent-discovery-plugin.js +69 -0
- package/plugins/llm-module-plugin.d.ts +10 -1
- package/plugins/llm-module-plugin.js +11 -3
- package/plugins/metering-plugin.d.ts +42 -0
- package/plugins/metering-plugin.js +178 -0
- package/plugins/text-mutation-plugin.d.ts +4 -0
- package/plugins/text-mutation-plugin.js +11 -1
- package/plugins/text-search-plugin.d.ts +4 -0
- package/plugins/text-search-plugin.js +13 -1
- package/preset.d.ts +21 -1
- package/preset.js +29 -2
- package/types.d.ts +47 -6
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* LlmMeteringPlugin
|
|
4
|
+
*
|
|
5
|
+
* Opt-in billing integration for graphile-llm. Completely separate from the
|
|
6
|
+
* pure LLM plugins (text-search, text-mutation, rag).
|
|
7
|
+
*
|
|
8
|
+
* **How it works:**
|
|
9
|
+
* 1. At schema build time, replaces `build.llmEmbedder` with a metered wrapper
|
|
10
|
+
* that has the same `(text: string) => Promise<number[]>` signature
|
|
11
|
+
* 2. At request time, wraps every root query/mutation resolver to set up a
|
|
12
|
+
* request-scoped MeteringContext via AsyncLocalStorage
|
|
13
|
+
* 3. When the embedder is called (by any plugin), the wrapper checks
|
|
14
|
+
* AsyncLocalStorage for a metering context and if found, calls
|
|
15
|
+
* check_billing_quota before and record_usage after
|
|
16
|
+
* 4. If quota is exceeded, the wrapper returns null — the calling plugin sees
|
|
17
|
+
* null and handles it (search falls back to text-only, mutations throw)
|
|
18
|
+
*
|
|
19
|
+
* The pure plugins never import metering, config-cache, or billing types.
|
|
20
|
+
* They call the embedder and handle null results — that's it.
|
|
21
|
+
*
|
|
22
|
+
* **Entity ID resolution:**
|
|
23
|
+
* The billing `entity_id` is resolved via a configurable callback.
|
|
24
|
+
* Default: reads `jwt.claims.user_id` from pgSettings. Override via
|
|
25
|
+
* `metering.resolveEntityId` in GraphileLlmPreset options.
|
|
26
|
+
*
|
|
27
|
+
* **Graceful behavior:**
|
|
28
|
+
* - billing_module not provisioned → embedder passes through unmetered
|
|
29
|
+
* - entity_id not available → embedder passes through unmetered
|
|
30
|
+
* - check_billing_quota throws → call is allowed (billing is opt-in)
|
|
31
|
+
* - record_usage throws → call succeeds, recording silently skipped
|
|
32
|
+
* - quota exceeded → embedder returns null
|
|
33
|
+
*/
|
|
34
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
35
|
+
exports.createLlmMeteringPlugin = createLlmMeteringPlugin;
|
|
36
|
+
const node_async_hooks_1 = require("node:async_hooks");
|
|
37
|
+
const metering_1 = require("../metering");
|
|
38
|
+
const config_cache_1 = require("../config-cache");
|
|
39
|
+
// ─── Request-scoped context via AsyncLocalStorage ───────────────────────────
|
|
40
|
+
const meteringStore = new node_async_hooks_1.AsyncLocalStorage();
|
|
41
|
+
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
42
|
+
function defaultResolveEntityId(pgSettings) {
|
|
43
|
+
return pgSettings['jwt.claims.user_id'] ?? null;
|
|
44
|
+
}
|
|
45
|
+
async function buildMeteringContext(graphqlContext, resolveEntityId) {
|
|
46
|
+
const pgSettings = graphqlContext?.pgSettings ?? {};
|
|
47
|
+
const entityId = resolveEntityId(pgSettings);
|
|
48
|
+
const databaseId = pgSettings['jwt.claims.database_id'] ?? null;
|
|
49
|
+
const requestId = pgSettings['request.id'] ?? null;
|
|
50
|
+
const actorId = pgSettings['jwt.claims.user_id'] ?? null;
|
|
51
|
+
if (!entityId || !databaseId)
|
|
52
|
+
return null;
|
|
53
|
+
const withPgClient = graphqlContext?.withPgClient;
|
|
54
|
+
if (!withPgClient)
|
|
55
|
+
return null;
|
|
56
|
+
let billingConfig = null;
|
|
57
|
+
let inferenceLogConfig = null;
|
|
58
|
+
try {
|
|
59
|
+
await withPgClient(pgSettings, async (pgClient) => {
|
|
60
|
+
const entry = await (0, config_cache_1.getLlmBillingConfig)(pgClient, databaseId);
|
|
61
|
+
billingConfig = entry.billing;
|
|
62
|
+
inferenceLogConfig = entry.inferenceLog;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
if (!billingConfig)
|
|
69
|
+
return null;
|
|
70
|
+
return {
|
|
71
|
+
withPgClient,
|
|
72
|
+
pgSettings,
|
|
73
|
+
billing: billingConfig,
|
|
74
|
+
entityId,
|
|
75
|
+
requestId,
|
|
76
|
+
databaseId,
|
|
77
|
+
actorId,
|
|
78
|
+
inferenceLog: inferenceLogConfig,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Wrap an embedder with metering that reads context from AsyncLocalStorage.
|
|
83
|
+
* The returned function has the same signature as the original embedder,
|
|
84
|
+
* so downstream plugins are unaware of billing.
|
|
85
|
+
*
|
|
86
|
+
* When no metering context is in scope, the original embedder is called directly.
|
|
87
|
+
* When quota is exceeded, returns null instead of a vector.
|
|
88
|
+
*/
|
|
89
|
+
function wrapEmbedderWithMetering(embedder, meteringOptions) {
|
|
90
|
+
return async (text) => {
|
|
91
|
+
const ctx = meteringStore.getStore();
|
|
92
|
+
if (!ctx) {
|
|
93
|
+
// No metering context in scope — call original embedder directly
|
|
94
|
+
const startTime = Date.now();
|
|
95
|
+
const result = await embedder(text);
|
|
96
|
+
const latencyMs = Date.now() - startTime;
|
|
97
|
+
console.log(`[graphile-llm] Embed (unmetered): dims=${result?.length ?? 0}, latency=${latencyMs}ms`);
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
const result = await (0, metering_1.meteredEmbed)(embedder, text, ctx, meteringOptions);
|
|
101
|
+
if (result.quotaExceeded) {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
return result.result;
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
// ─── Plugin ─────────────────────────────────────────────────────────────────
|
|
108
|
+
function createLlmMeteringPlugin(meteringConfig = {}) {
|
|
109
|
+
const { embeddingMeterSlug: configEmbeddingSlug, chatMeterSlug: configChatSlug, skipMetering, resolveEntityId = defaultResolveEntityId, } = meteringConfig;
|
|
110
|
+
return {
|
|
111
|
+
name: 'LlmMeteringPlugin',
|
|
112
|
+
version: '0.2.0',
|
|
113
|
+
description: 'Wraps LLM embedder/chat with billing quota checks and usage recording',
|
|
114
|
+
after: ['LlmModulePlugin'],
|
|
115
|
+
before: ['LlmTextSearchPlugin', 'LlmTextMutationPlugin', 'LlmRagPlugin'],
|
|
116
|
+
schema: {
|
|
117
|
+
hooks: {
|
|
118
|
+
build(build) {
|
|
119
|
+
const originalEmbedder = build.llmEmbedder;
|
|
120
|
+
if (!originalEmbedder) {
|
|
121
|
+
console.log('[graphile-llm] Metering plugin loaded but no embedder configured — skipping');
|
|
122
|
+
return build;
|
|
123
|
+
}
|
|
124
|
+
// Meter slug = model name by default (three-level waterfall: model → inference → universal)
|
|
125
|
+
const embeddingModel = build.llmEmbeddingModel;
|
|
126
|
+
const chatModel = build.llmChatModel;
|
|
127
|
+
const embeddingSlug = configEmbeddingSlug ?? embeddingModel ?? undefined;
|
|
128
|
+
const chatSlug = configChatSlug ?? chatModel ?? undefined;
|
|
129
|
+
if (embeddingSlug) {
|
|
130
|
+
console.log(`[graphile-llm] Metering enabled — embedding meter: ${embeddingSlug}`);
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
console.log('[graphile-llm] Metering enabled but no embedding model name — usage will not be metered');
|
|
134
|
+
}
|
|
135
|
+
const meteringOptions = {
|
|
136
|
+
embeddingMeterSlug: embeddingSlug,
|
|
137
|
+
chatMeterSlug: chatSlug,
|
|
138
|
+
skipMetering,
|
|
139
|
+
embeddingModel: embeddingModel ?? undefined,
|
|
140
|
+
chatModel: chatModel ?? undefined,
|
|
141
|
+
};
|
|
142
|
+
// Replace the embedder with a metered version.
|
|
143
|
+
// Same signature except it can return null (quota exceeded).
|
|
144
|
+
const meteredEmbedder = wrapEmbedderWithMetering(originalEmbedder, meteringOptions);
|
|
145
|
+
return build.extend(build, {
|
|
146
|
+
llmEmbedder: meteredEmbedder,
|
|
147
|
+
}, 'LlmMeteringPlugin replacing llmEmbedder with metered version');
|
|
148
|
+
},
|
|
149
|
+
/**
|
|
150
|
+
* Wrap every root query/mutation resolver to establish the
|
|
151
|
+
* request-scoped metering context via AsyncLocalStorage.
|
|
152
|
+
*/
|
|
153
|
+
GraphQLObjectType_fields_field(field, build, context) {
|
|
154
|
+
const { scope: { isRootQuery, isRootMutation }, } = context;
|
|
155
|
+
if (!isRootQuery && !isRootMutation)
|
|
156
|
+
return field;
|
|
157
|
+
// Only wrap if we actually replaced the embedder
|
|
158
|
+
if (!build.llmEmbedder)
|
|
159
|
+
return field;
|
|
160
|
+
const defaultResolver = (obj) => obj[context.scope.fieldName];
|
|
161
|
+
const { resolve: oldResolve = defaultResolver, ...rest } = field;
|
|
162
|
+
return {
|
|
163
|
+
...rest,
|
|
164
|
+
async resolve(source, args, graphqlContext, info) {
|
|
165
|
+
// Build the metering context for this request
|
|
166
|
+
const ctx = await buildMeteringContext(graphqlContext, resolveEntityId);
|
|
167
|
+
// Run the original resolver within the AsyncLocalStorage scope
|
|
168
|
+
// so any embedder calls made by downstream plugins pick up the ctx
|
|
169
|
+
return meteringStore.run(ctx, () => {
|
|
170
|
+
return oldResolve(source, args, graphqlContext, info);
|
|
171
|
+
});
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
* Example:
|
|
10
10
|
* mutation { createArticle(input: { embeddingText: "Machine learning concepts" }) }
|
|
11
11
|
*
|
|
12
|
+
* If the embedder returns null (e.g. quota exceeded when the metering plugin
|
|
13
|
+
* is loaded), the mutation throws an error — unlike search, mutations cannot
|
|
14
|
+
* silently skip writing a vector the user asked for.
|
|
15
|
+
*
|
|
12
16
|
* This is the mutation counterpart to LlmTextSearchPlugin (which handles
|
|
13
17
|
* filter/query-side text-to-vector). Together they let clients work entirely
|
|
14
18
|
* with text/prompts instead of raw float vectors.
|
|
@@ -10,6 +10,10 @@
|
|
|
10
10
|
* Example:
|
|
11
11
|
* mutation { createArticle(input: { embeddingText: "Machine learning concepts" }) }
|
|
12
12
|
*
|
|
13
|
+
* If the embedder returns null (e.g. quota exceeded when the metering plugin
|
|
14
|
+
* is loaded), the mutation throws an error — unlike search, mutations cannot
|
|
15
|
+
* silently skip writing a vector the user asked for.
|
|
16
|
+
*
|
|
13
17
|
* This is the mutation counterpart to LlmTextSearchPlugin (which handles
|
|
14
18
|
* filter/query-side text-to-vector). Together they let clients work entirely
|
|
15
19
|
* with text/prompts instead of raw float vectors.
|
|
@@ -64,7 +68,7 @@ function getTextToVectorMapping(pgCodec, build) {
|
|
|
64
68
|
function createLlmTextMutationPlugin() {
|
|
65
69
|
return {
|
|
66
70
|
name: 'LlmTextMutationPlugin',
|
|
67
|
-
version: '0.
|
|
71
|
+
version: '0.2.0',
|
|
68
72
|
description: 'Adds text companion fields on mutation inputs for vector columns — ' +
|
|
69
73
|
'text is embedded server-side before storing',
|
|
70
74
|
after: [
|
|
@@ -124,6 +128,8 @@ function createLlmTextMutationPlugin() {
|
|
|
124
128
|
* Uses the same v4-style resolver wrapping pattern as graphile-upload-plugin
|
|
125
129
|
* and graphile-bucket-provisioner-plugin. grafserv v5 supports this through
|
|
126
130
|
* its backwards-compatibility layer.
|
|
131
|
+
*
|
|
132
|
+
* If the embedder returns null (e.g. quota exceeded), throws an error.
|
|
127
133
|
*/
|
|
128
134
|
GraphQLObjectType_fields_field(field, build, context) {
|
|
129
135
|
const { scope: { isRootMutation, fieldName, pgCodec }, } = context;
|
|
@@ -166,6 +172,10 @@ function createLlmTextMutationPlugin() {
|
|
|
166
172
|
const startTime = Date.now();
|
|
167
173
|
const vector = await embedder(value);
|
|
168
174
|
const latencyMs = Date.now() - startTime;
|
|
175
|
+
if (vector === null) {
|
|
176
|
+
throw new Error(`EMBED_QUOTA_EXCEEDED: Cannot embed ${key} — embedding quota exceeded. ` +
|
|
177
|
+
'Upgrade your plan or wait for the next billing period.');
|
|
178
|
+
}
|
|
169
179
|
console.log(`[graphile-llm] Mutation embed: field=${key}, dims=${vector.length}, latency=${latencyMs}ms`);
|
|
170
180
|
// Inject the vector into the corresponding field
|
|
171
181
|
obj[vectorFieldName] = vector;
|
|
@@ -22,6 +22,10 @@
|
|
|
22
22
|
*
|
|
23
23
|
* If the embedder is not configured, the `text` field is still registered
|
|
24
24
|
* (so the schema is stable) but will return a clear error at execution time.
|
|
25
|
+
*
|
|
26
|
+
* If the embedder returns null (e.g. quota exceeded when the metering
|
|
27
|
+
* plugin is loaded), the text field is silently removed — the query
|
|
28
|
+
* continues with text-only search as a graceful fallback.
|
|
25
29
|
*/
|
|
26
30
|
import type { GraphileConfig } from 'graphile-config';
|
|
27
31
|
declare global {
|
|
@@ -23,6 +23,10 @@
|
|
|
23
23
|
*
|
|
24
24
|
* If the embedder is not configured, the `text` field is still registered
|
|
25
25
|
* (so the schema is stable) but will return a clear error at execution time.
|
|
26
|
+
*
|
|
27
|
+
* If the embedder returns null (e.g. quota exceeded when the metering
|
|
28
|
+
* plugin is loaded), the text field is silently removed — the query
|
|
29
|
+
* continues with text-only search as a graceful fallback.
|
|
26
30
|
*/
|
|
27
31
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
32
|
exports.createLlmTextSearchPlugin = createLlmTextSearchPlugin;
|
|
@@ -41,6 +45,9 @@ function hasVectorColumns(pgCodec) {
|
|
|
41
45
|
/**
|
|
42
46
|
* Recursively walk a `where` argument object and embed any VectorNearbyInput
|
|
43
47
|
* values that have `text` instead of `vector`.
|
|
48
|
+
*
|
|
49
|
+
* If the embedder returns null (e.g. quota exceeded), the text field is
|
|
50
|
+
* removed so the pgvector filter is skipped — graceful text-only fallback.
|
|
44
51
|
*/
|
|
45
52
|
async function embedTextInWhere(obj, embedder) {
|
|
46
53
|
if (!obj || typeof obj !== 'object')
|
|
@@ -56,6 +63,11 @@ async function embedTextInWhere(obj, embedder) {
|
|
|
56
63
|
const startTime = Date.now();
|
|
57
64
|
const vector = await embedder(value.text);
|
|
58
65
|
const latencyMs = Date.now() - startTime;
|
|
66
|
+
if (vector === null) {
|
|
67
|
+
// Embedder returned null (e.g. quota exceeded) — skip vector search
|
|
68
|
+
delete value.text;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
59
71
|
console.log(`[graphile-llm] Search embed: field=${key}, dims=${vector.length}, latency=${latencyMs}ms`);
|
|
60
72
|
// Replace text with vector
|
|
61
73
|
value.vector = vector;
|
|
@@ -88,7 +100,7 @@ async function embedTextInWhere(obj, embedder) {
|
|
|
88
100
|
function createLlmTextSearchPlugin() {
|
|
89
101
|
return {
|
|
90
102
|
name: 'LlmTextSearchPlugin',
|
|
91
|
-
version: '0.
|
|
103
|
+
version: '0.2.0',
|
|
92
104
|
description: 'Adds text-to-vector embedding support on VectorNearbyInput filter fields',
|
|
93
105
|
after: [
|
|
94
106
|
'LlmModulePlugin',
|
package/preset.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* - Resolves an embedder from configuration (llm_module, env vars, or preset options)
|
|
9
9
|
* - Adds a `text: String` field to `VectorNearbyInput` for text-based vector search
|
|
10
10
|
* - Adds `{column}Text: String` companion fields on mutation inputs for vector columns
|
|
11
|
-
* -
|
|
11
|
+
* - Optionally enables billing/metering via the LlmMeteringPlugin
|
|
12
12
|
*
|
|
13
13
|
* This preset is standalone — it is NOT included in ConstructivePreset by default.
|
|
14
14
|
* Projects that want LLM features opt in by adding it to their preset.
|
|
@@ -42,6 +42,26 @@
|
|
|
42
42
|
* ],
|
|
43
43
|
* };
|
|
44
44
|
* ```
|
|
45
|
+
*
|
|
46
|
+
* @example With billing metering (opt-in, meter slug = model name by default):
|
|
47
|
+
* ```typescript
|
|
48
|
+
* GraphileLlmPreset({
|
|
49
|
+
* defaultEmbedder: { provider: 'openai', model: 'text-embedding-3-small' },
|
|
50
|
+
* metering: true,
|
|
51
|
+
* // → embedding calls metered under 'text-embedding-3-small' meter slug
|
|
52
|
+
* // → three-level waterfall: text-embedding-3-small → inference pool → universal
|
|
53
|
+
* })
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* @example With custom entity_id resolution (bill per-database):
|
|
57
|
+
* ```typescript
|
|
58
|
+
* GraphileLlmPreset({
|
|
59
|
+
* defaultEmbedder: { provider: 'openai', model: 'text-embedding-3-small' },
|
|
60
|
+
* metering: {
|
|
61
|
+
* resolveEntityId: (pgSettings) => pgSettings['jwt.claims.database_id'],
|
|
62
|
+
* },
|
|
63
|
+
* })
|
|
64
|
+
* ```
|
|
45
65
|
*/
|
|
46
66
|
import type { GraphileConfig } from 'graphile-config';
|
|
47
67
|
import type { GraphileLlmOptions } from './types';
|
package/preset.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* - Resolves an embedder from configuration (llm_module, env vars, or preset options)
|
|
10
10
|
* - Adds a `text: String` field to `VectorNearbyInput` for text-based vector search
|
|
11
11
|
* - Adds `{column}Text: String` companion fields on mutation inputs for vector columns
|
|
12
|
-
* -
|
|
12
|
+
* - Optionally enables billing/metering via the LlmMeteringPlugin
|
|
13
13
|
*
|
|
14
14
|
* This preset is standalone — it is NOT included in ConstructivePreset by default.
|
|
15
15
|
* Projects that want LLM features opt in by adding it to their preset.
|
|
@@ -43,6 +43,26 @@
|
|
|
43
43
|
* ],
|
|
44
44
|
* };
|
|
45
45
|
* ```
|
|
46
|
+
*
|
|
47
|
+
* @example With billing metering (opt-in, meter slug = model name by default):
|
|
48
|
+
* ```typescript
|
|
49
|
+
* GraphileLlmPreset({
|
|
50
|
+
* defaultEmbedder: { provider: 'openai', model: 'text-embedding-3-small' },
|
|
51
|
+
* metering: true,
|
|
52
|
+
* // → embedding calls metered under 'text-embedding-3-small' meter slug
|
|
53
|
+
* // → three-level waterfall: text-embedding-3-small → inference pool → universal
|
|
54
|
+
* })
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* @example With custom entity_id resolution (bill per-database):
|
|
58
|
+
* ```typescript
|
|
59
|
+
* GraphileLlmPreset({
|
|
60
|
+
* defaultEmbedder: { provider: 'openai', model: 'text-embedding-3-small' },
|
|
61
|
+
* metering: {
|
|
62
|
+
* resolveEntityId: (pgSettings) => pgSettings['jwt.claims.database_id'],
|
|
63
|
+
* },
|
|
64
|
+
* })
|
|
65
|
+
* ```
|
|
46
66
|
*/
|
|
47
67
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
48
68
|
exports.GraphileLlmPreset = GraphileLlmPreset;
|
|
@@ -50,6 +70,7 @@ const llm_module_plugin_1 = require("./plugins/llm-module-plugin");
|
|
|
50
70
|
const text_search_plugin_1 = require("./plugins/text-search-plugin");
|
|
51
71
|
const text_mutation_plugin_1 = require("./plugins/text-mutation-plugin");
|
|
52
72
|
const rag_plugin_1 = require("./plugins/rag-plugin");
|
|
73
|
+
const metering_plugin_1 = require("./plugins/metering-plugin");
|
|
53
74
|
/**
|
|
54
75
|
* Creates a preset that includes all LLM plugins.
|
|
55
76
|
*
|
|
@@ -57,10 +78,16 @@ const rag_plugin_1 = require("./plugins/rag-plugin");
|
|
|
57
78
|
* @returns A GraphileConfig.Preset to add to your extends array
|
|
58
79
|
*/
|
|
59
80
|
function GraphileLlmPreset(options = {}) {
|
|
60
|
-
const { enableTextSearch = true, enableTextMutations = true, enableRag = false, ragDefaults, } = options;
|
|
81
|
+
const { enableTextSearch = true, enableTextMutations = true, enableRag = false, ragDefaults, metering, } = options;
|
|
61
82
|
const plugins = [
|
|
62
83
|
(0, llm_module_plugin_1.createLlmModulePlugin)(options),
|
|
63
84
|
];
|
|
85
|
+
// Metering is opt-in: only loaded when metering is truthy
|
|
86
|
+
// (true, or a MeteringConfig object)
|
|
87
|
+
if (metering) {
|
|
88
|
+
const meteringConfig = metering === true ? {} : metering;
|
|
89
|
+
plugins.push((0, metering_plugin_1.createLlmMeteringPlugin)(meteringConfig));
|
|
90
|
+
}
|
|
64
91
|
if (enableTextSearch) {
|
|
65
92
|
plugins.push((0, text_search_plugin_1.createLlmTextSearchPlugin)());
|
|
66
93
|
}
|
package/types.d.ts
CHANGED
|
@@ -17,8 +17,6 @@ export interface EmbedderConfig {
|
|
|
17
17
|
model?: string;
|
|
18
18
|
/** Base URL for the provider (e.g. 'http://localhost:11434' for Ollama) */
|
|
19
19
|
baseUrl?: string;
|
|
20
|
-
/** API key for providers that require authentication (e.g. OpenAI) */
|
|
21
|
-
apiKey?: string;
|
|
22
20
|
}
|
|
23
21
|
/**
|
|
24
22
|
* A single message in a chat conversation.
|
|
@@ -50,8 +48,6 @@ export interface ChatConfig {
|
|
|
50
48
|
model?: string;
|
|
51
49
|
/** Base URL for the provider */
|
|
52
50
|
baseUrl?: string;
|
|
53
|
-
/** API key for providers that require authentication */
|
|
54
|
-
apiKey?: string;
|
|
55
51
|
}
|
|
56
52
|
/**
|
|
57
53
|
* The shape of the `llm_module` data stored in `services_public.api_modules`.
|
|
@@ -74,8 +70,6 @@ export interface LlmModuleData {
|
|
|
74
70
|
chat_model?: string;
|
|
75
71
|
/** Base URL for the chat provider */
|
|
76
72
|
chat_base_url?: string;
|
|
77
|
-
/** API key reference (e.g. 'vault://openai-key' or env var name) */
|
|
78
|
-
api_key_ref?: string;
|
|
79
73
|
/** Rate limit: requests per minute */
|
|
80
74
|
rate_limit_rpm?: number;
|
|
81
75
|
/** Maximum tokens per request */
|
|
@@ -131,6 +125,41 @@ export interface ChunkTableInfo {
|
|
|
131
125
|
/** Text content column on chunks table (the actual chunk text) */
|
|
132
126
|
contentField: string;
|
|
133
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* Configuration for billing/metering integration.
|
|
130
|
+
* When provided, embedding and chat calls are wrapped with quota checks
|
|
131
|
+
* and usage recording via the billing_module functions.
|
|
132
|
+
*/
|
|
133
|
+
export interface MeteringConfig {
|
|
134
|
+
/**
|
|
135
|
+
* Meter slug for embedding operations.
|
|
136
|
+
* Must match a slug in the billing_module meters table.
|
|
137
|
+
*
|
|
138
|
+
* @default the embedding model name (e.g. 'text-embedding-3-small')
|
|
139
|
+
* — meter slug = model name, so each model has its own meter
|
|
140
|
+
* in the three-level waterfall (per-model → inference pool → universal).
|
|
141
|
+
*/
|
|
142
|
+
embeddingMeterSlug?: string;
|
|
143
|
+
/**
|
|
144
|
+
* Meter slug for chat completion operations.
|
|
145
|
+
*
|
|
146
|
+
* @default the chat model name (e.g. 'gpt-4o-mini')
|
|
147
|
+
*/
|
|
148
|
+
chatMeterSlug?: string;
|
|
149
|
+
/**
|
|
150
|
+
* Disable metering entirely (e.g. for local dev).
|
|
151
|
+
* When true, billing functions are never called.
|
|
152
|
+
* @default false
|
|
153
|
+
*/
|
|
154
|
+
skipMetering?: boolean;
|
|
155
|
+
/**
|
|
156
|
+
* Resolve the billing entity_id from pgSettings.
|
|
157
|
+
* The entity_id identifies who gets billed (user, org, etc.).
|
|
158
|
+
*
|
|
159
|
+
* @default reads jwt.claims.user_id
|
|
160
|
+
*/
|
|
161
|
+
resolveEntityId?: (pgSettings: Record<string, string>) => string | null;
|
|
162
|
+
}
|
|
134
163
|
/**
|
|
135
164
|
* Options for the GraphileLlmPreset.
|
|
136
165
|
*/
|
|
@@ -170,4 +199,16 @@ export interface GraphileLlmOptions {
|
|
|
170
199
|
* Individual queries can override these values.
|
|
171
200
|
*/
|
|
172
201
|
ragDefaults?: RagDefaults;
|
|
202
|
+
/**
|
|
203
|
+
* Billing/metering configuration (opt-in).
|
|
204
|
+
* When truthy, loads the LlmMeteringPlugin which wraps the embedder
|
|
205
|
+
* with billing quota checks + usage recording.
|
|
206
|
+
*
|
|
207
|
+
* Set to `true` to enable metering with defaults (entity_id from jwt.claims.user_id).
|
|
208
|
+
* Provide a MeteringConfig object for fine-grained control (custom entity_id, meter slugs).
|
|
209
|
+
* Set to `false` or omit to disable metering entirely.
|
|
210
|
+
*
|
|
211
|
+
* @default undefined (metering disabled)
|
|
212
|
+
*/
|
|
213
|
+
metering?: boolean | MeteringConfig;
|
|
173
214
|
}
|