feat(graphile-llm): wire billing metering into LLM plugins#1192
Open
pyramation wants to merge 6 commits into
Open
feat(graphile-llm): wire billing metering into LLM plugins#1192pyramation wants to merge 6 commits into
pyramation wants to merge 6 commits into
Conversation
Add per-database billing integration to the graphile-llm package: - config-cache.ts: LRU cache (5-min TTL, 50 entries) for billing_module metadata and API key resolution from app_secrets per database_id - metering.ts: billing-aware wrappers (meteredEmbed, meteredChat) that call check_billing_quota() before and record_usage() after LLM calls - LlmModulePlugin: exposes metering options on the build context - LlmTextSearchPlugin: metered embedding with graceful degradation — when quota exceeded, skips vector path (text-only search continues) - LlmTextMutationPlugin: metered embedding that throws QuotaExceededError on mutations (can't silently skip writing a vector the user asked for) - MeteringConfig on GraphileLlmOptions: configurable meter slugs, estimated tokens, and skip toggle. Auto-detects billing_module. - Uses Graphile withPgClient pattern for all billing SQL calls Billing functions (check_billing_quota, record_usage) are resolved from the tenant database's billing_module metaschema. When billing is not provisioned, all calls pass through unmetered.
Contributor
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
…Plugin - Extract all billing/metering logic into metering-plugin.ts - LlmModulePlugin, TextSearchPlugin, TextMutationPlugin are now pure (no billing imports, no metering context building) - LlmMeteringPlugin uses AsyncLocalStorage to transparently wrap the embedder with quota checks — downstream plugins are unaware of billing - Entity ID resolved via configurable callback (default: jwt.claims.user_id) instead of non-existent jwt.claims.membership_id - Metering is opt-in: only loaded when metering option is truthy - Add schema-existence guard in config-cache (checks metaschema_modules_public exists before querying billing_module table) - Graceful degradation: missing schema, missing entity_id, or failed billing calls all result in unmetered passthrough
- LlmModulePlugin now exposes llmEmbeddingModel and llmChatModel on build - LlmMeteringPlugin reads model names from build and uses them as default meter slugs (e.g. 'text-embedding-3-small' → billing meters table) - Three-level waterfall: per-model → inference pool → universal credits (handled by billing module's category_meter field) - Remove hardcoded 'embedding_tokens'/'chat_tokens' defaults - Add docs/spec/llm-metering.md — full architecture reference for two-tier billing, model=meter slug convention, and waterfall
…user_module The table was renamed from metaschema_modules_public.encrypted_secrets_module to metaschema_modules_public.config_secrets_user_module. Also updated the JOIN column from private_schema_id to schema_id to match the new schema.
…t length Removed the configurable estimatedEmbeddingTokens option — token counts are now estimated directly from the input text length (~4 chars/token). No tokenizer needed since the billing system uses tokens as abstract units and the credit_cost per model normalizes relative expense.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Wire billing metering infrastructure into the
graphile-llmpackage with clean architectural separation between pure LLM plugins and opt-in billing.Key design: meter slug = model name
Each LLM model gets its own billing meter. The meter slug IS the model name — no mapping, no guessing:
Three-level waterfall (handled by billing module's
category_meter):Architecture
Pure plugins (no billing dependency):
LlmModulePlugin— resolves embedder + chat completer from config/env, exposes model names on buildLlmTextSearchPlugin— addstext: StringtoVectorNearbyInput, embeds text server-sideLlmTextMutationPlugin— adds{column}Text: Stringcompanion fields on mutation inputsOpt-in metering (separate plugin):
LlmMeteringPlugin— transparently wrapsbuild.llmEmbedderwith billing quota checks + usage recording viaAsyncLocalStoragellmEmbeddingModel,llmChatModel) and uses them as default meter slugsresolveEntityIdcallback (default:jwt.claims.user_id)Supporting utilities:
config-cache.ts— LRU cache (5-min TTL, max 50) for billing_module metadata per database_id. Schema-existence guard checksinformation_schema.schematabefore querying.metering.ts—meteredEmbed()/meteredChat()wrappersUsage
Two-tier billing model
Documented in
docs/spec/llm-metering.md:Review & Testing Checklist for Human
AsyncLocalStorageapproach inmetering-plugin.tshandles concurrent requests correctlyinformation_schema.schemataguard inconfig-cache.tsworks for databases withoutmetaschema_modules_publicresolveEntityIddefault (jwt.claims.user_id) — for platform-tier billing, you'd wantjwt.claims.database_idinsteaddocs/spec/llm-metering.mdfor accuracy of the two-tier billing model and waterfall designcategory_meter = 'inference'Recommended test plan: Set up a database with billing_module, seed model-name meters with
category_meter = 'inference', configuremetering: true, and run embedding queries. Verifyrecord_usageentries appear in the ledger under the model name slug.Notes
docs/spec/llm-metering.mdis the canonical reference for the metering architecture. It covers the two-tier model, meter slug convention, waterfall, and graceful degradation.Link to Devin session: https://app.devin.ai/sessions/2b5a29d83d3f478e8d3d972653b4879c
Requested by: @pyramation