feat(graphile-llm): add inference usage logging to metering plugin#1196
Open
pyramation wants to merge 7 commits into
Open
feat(graphile-llm): add inference usage logging to metering plugin#1196pyramation wants to merge 7 commits into
pyramation wants to merge 7 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.
…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.
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:
|
Adds inline INSERT into usage_log_inference table after billing record_usage calls in both meteredEmbed and meteredChat functions. Changes: - config-cache.ts: Add InferenceLogConfig type and resolution from inference_log_module metaschema table (cached alongside billing config) - metering.ts: Add InferenceLogEntry type, logInferenceUsage helper, and calls after billing in meteredEmbed/meteredChat (including quota_exceeded events). Add databaseId, actorId, inferenceLog to MeteringContext. Add embeddingModel, chatModel, provider to MeteringOptions. - metering-plugin.ts: Wire databaseId, actorId, inferenceLog into MeteringContext. Pass model names to MeteringOptions. - index.ts: Export new types (InferenceLogEntry, InferenceLogConfig) and logInferenceUsage function. Gracefully skips if inference_log_module is not provisioned. TODO: dual-write to child (generated) database for platform aggregation.
d2463b7 to
df79e9e
Compare
3c6b433 to
3a257e3
Compare
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
Adds inline
INSERT INTO usage_log_inferenceto theLlmMeteringPlugin, writing to the parent database alongside the existing billingrecord_usagecalls. This is Approach 1 from the metering architecture discussion — simple, SQL straight up, no new packages.What changed
config-cache.tsInferenceLogConfigtype (schema + table name)INFERENCE_LOG_MODULE_SQLquery to resolve the inference log module's schema/table frommetaschema_modules_public.inference_log_moduleresolveInferenceLogConfig()— checks if schema exists, queries module config, returns null if not provisionedgetLlmBillingConfig()now resolves inference log config in parallel with billing + API keymetering.tsMeteringContextexpanded withdatabaseId,actorId,inferenceLogMeteringOptionsexpanded withembeddingModel,chatModel,provider(for log entries)InferenceLogEntryinterface — typed payload matchingusage_log_inferencecolumnslogInferenceUsage()— parameterized INSERT, graceful skip if module not provisioned,catchlogs warning but never throwsmeteredEmbed— logs after billing on both success and quota_exceeded pathsmeteredChat— logs after billing on both success and quota_exceeded pathsmetering-plugin.tsbuildMeteringContextnow extractsactorIdfromjwt.claims.user_idand readsinferenceLogfrom the cached config entryembeddingModelandchatModeltoMeteringOptionsindex.tslogInferenceUsage,InferenceLogEntry,InferenceLogConfigDesign decisions
withPgClient. Child DB / platform dual-write is a TODO comment for future work.inference_log_moduleis not provisioned,inferenceLogisnullandlogInferenceUsagereturns immediately. If the INSERT fails, it logs a warning but never throws.status: 'quota_exceeded'events so the usage table captures denied requests too.Depends on
feat/llm-billing-metering) — base branch, provides metering.ts + config-cache.ts + metering-plugin.tsinference_log_modulegenerator that creates theusage_log_inferencetableReview & Testing Checklist for Human
inference_log_modulegenerator output (16 columns: database_id through error_type)logInferenceUsagenever throws — thecatchin both call sites + the try/catch inside the function itself should make this bulletproofresolveInferenceLogConfigcorrectly guards against missingmetaschema_modules_publicschemainference_log_moduleprovisioned — verify rows appear inusage_log_inferenceafter embedding/chat callsinference_log_module— verify no errors, metering/billing still works normallyNotes
providerfield is not yet populated (alwaysnull) since the currentLlmModulePlugindoesn't expose provider info on the build context. This can be wired in a follow-up.graphile-usage-logplugin for generic multi-category logging with routing (platform/app/dual) — tracked in #901Link to Devin session: https://app.devin.ai/sessions/2b5a29d83d3f478e8d3d972653b4879c
Requested by: @pyramation