Scrawn LogoScrawn Docs
SDK ReferenceFunctionsAI Token Billing

Overview

Meter AI token usage by streaming events to the backend

Stream token usage events directly with aiTokenStreamConsumer, or use the first-class Vercel AI SDK wrapper that auto-instruments every LLM call.

Stream Token Events

aiTokenStreamConsumer consumes an async iterable of AITokenUsagePayload objects and streams them to the backend for billing.

import { scrawn } from "@scrawn/core";

const biller = scrawn({
  apiKey: process.env.SCRAWN_KEY as `scrn_${string}`,
  baseURL: process.env.SCRAWN_BASE_URL || "http://localhost:8069",
});

async function* generateUsage() {
  yield {
    userId: "user-123",
    model: "gpt-4",
    inputTokens: 100,
    outputTokens: 50,
    inputDebit: 3,     // 3¢ per input token
    outputDebit: 6,    // 6¢ per output token
  };
}

const response = await biller.aiTokenStreamConsumer(generateUsage());
// → { eventsProcessed: 1 }

Fork Mode

Return a forked stream to simultaneously bill and stream tokens to the user:

async function* tokenStream() {
  yield {
    userId: "user-123",
    model: "gpt-4",
    inputTokens: 100,
    outputTokens: 50,
    inputDebit: 3,
    outputDebit: 6,
  };
}

const { response, stream } = await biller.aiTokenStreamConsumer(
  tokenStream(),
  { return: true }
);

// Stream tokens to user while billing runs in background
for await (const token of stream) {
  process.stdout.write(token.outputTokens.toString());
}

const result = await response;

AITokenUsagePayload

Each payload in the stream represents a single token usage event:

FieldTypeDescription
userIdstringUser to bill
modelstringModel identifier (e.g. "gpt-4")
inputTokensnumberInput token count
outputTokensnumberOutput token count
inputDebitDebitPricing for input tokens — number, tag, or expression
outputDebitDebitPricing for output tokens
providerstring(optional) LLM provider
inputCacheTokensnumber(optional) Cached input tokens
inputCacheDebitDebit(optional) Pricing for cached input
outputCacheTokensnumber(optional) Cached output tokens
outputCacheDebitDebit(optional) Pricing for cached output
metadataobject(optional) Arbitrary metadata

The Debit type accepts a number (cents), a biller.tag() reference, or a pricing expression using mul(), add(), inputTokens(), etc.