Server SDK and logging v1.0.0

ai-request-meter

Track AI usage, cost, latency, model performance, and local quality signals when developers call AI through your SDK.

Download & install

Install the SDK and PostgreSQL driver in the server application that makes AI calls.

Terminal
npm install ai-request-meter pg

Usage

Developers call AI through createAI(). After every response, the SDK logs tokens, model, latency, status, cost, and local scores.

Node / TypeScript
import { createAI, openaiProvider, postgresLogger } from 'ai-request-meter';

const ai = createAI({
  provider: openaiProvider({
    apiKey: process.env.OPENAI_API_KEY
  }),
  logger: postgresLogger({
    connectionString: process.env.DATABASE_URL
  })
});

const result = await ai.generate({
  taskName: 'customer_support_reply',
  model: 'gpt-4o-mini',
  messages: [
    { role: 'user', content: 'Write reply for this customer' }
  ]
});

PostgreSQL setup

Create the log table once. postgresLogger() inserts records automatically after successful and failed AI calls.

Migration SQL
create table if not exists ai_request_meter_logs (
  id text primary key,
  task_name text not null,
  provider text not null,
  model text not null,
  input_tokens integer not null default 0,
  output_tokens integer not null default 0,
  total_tokens integer not null default 0,
  estimated_cost numeric not null default 0,
  latency_ms integer not null default 0,
  status text not null,
  error_message text,
  quality_score integer not null default 0,
  content_score integer not null default 0,
  readiness_score integer not null default 0,
  scores jsonb not null default '{}'::jsonb,
  metadata jsonb not null default '{}'::jsonb,
  prompt_text text,
  response_text text,
  created_at timestamptz not null
);

Live tracking examples

Copy the pattern that matches your server workflow: PostgreSQL logging, metadata-only privacy, local console logs, or standalone scoring helpers.

Automatic PostgreSQL logging

Wrap OpenAI-compatible calls once and save every tracked response to PostgreSQL.

Example code
import { createAI, openaiProvider, postgresLogger } from 'ai-request-meter';

const ai = createAI({
  provider: openaiProvider({
    apiKey: process.env.OPENAI_API_KEY
  }),
  logger: postgresLogger({
    connectionString: process.env.DATABASE_URL
  })
});

const result = await ai.generate({
  taskName: 'customer_support_reply',
  model: 'gpt-4o-mini',
  messages: [
    { role: 'user', content: 'Write reply for this customer' }
  ]
});

Privacy-first metadata logging

Prompt and response text stay out of logs unless captureText is explicitly enabled.

Example code
const ai = createAI({
  provider,
  logger,
  captureText: false
});

Local console logger

Use consoleLogger while testing before connecting a database.

Example code
import { createAI, consoleLogger } from 'ai-request-meter';

const ai = createAI({
  provider,
  logger: consoleLogger()
});

Local heuristic scores

Estimate quality, content style, and page readiness without making another AI call.

Example code
import { scoreQuality, scoreContent, scoreReadiness } from 'ai-request-meter';

const quality = scoreQuality(responseText);
const content = scoreContent(responseText);
const readiness = scoreReadiness({
  title,
  description,
  headings,
  content: pageText
});

API reference

The public API stays small: one tracked client, one OpenAI-compatible provider, three loggers, and deterministic scoring helpers.

APIPurpose
createAI(config)Creates a tracked AI client with provider, logger, privacy, pricing, and logger-failure options.
ai.generate(options)Runs one text chat-completion style request and logs the normalized result.
openaiProvider(options)Calls OpenAI-compatible /chat/completions APIs with apiKey, baseURL, headers, timeout, and fetcher options.
postgresLogger(options)Writes normalized log records into PostgreSQL table ai_request_meter_logs.
consoleLogger()Writes normalized records to a local sink for development.
noopLogger()Disables logging while keeping the same SDK call shape.
estimateCost(options)Estimates input/output token cost with default or custom per-model pricing.
scoreQuality(text)Scores clarity, usefulness, confidence, and safety using local heuristics.
scoreContent(text)Estimates AI-likelihood, repetition, readability, and tone.
scoreReadiness(input)Scores SEO/content structure/accessibility metadata from explicit page input.

Privacy defaults

By default, prompt and response text are opt-in. ai-request-meter stores metadata, token usage, estimated cost, status, latency, and scores unless captureText: true is configured.

DefaultNo promptText or responseText
Opt-inUse captureText only when your app policy allows it
Logger errorsSwallowed by default; set failOnLoggerError for strict pipelines

Example log record

A saved record gives product and engineering teams enough information to understand usage without storing sensitive text by default.

JSON
{
  "taskName": "customer_support_reply",
  "model": "gpt-4o-mini",
  "inputTokens": 420,
  "outputTokens": 95,
  "totalTokens": 515,
  "estimatedCost": 0.00012,
  "latencyMs": 1300,
  "status": "success",
  "qualityScore": 71,
  "contentScore": 96,
  "readinessScore": 68,
  "createdAt": "2026-09-28T10:30:00.000Z"
}