SuperPenguin Docs
SDKsTypeScript

TypeScript SDK overview

Install and initialize @superpenguin/js for server-side AI cost attribution.

@superpenguin/js wraps native provider SDKs and supports Vercel AI SDK helpers, OpenTelemetry span ingestion, and OpenAI Realtime sessions.

The SDK OTel helper is distinct from hosted OTLP ingestion, where OpenRouter or an exporter sends OTLP JSON directly.

Use this SDK in server code only. Do not expose SP_API_KEY to browsers.

Install

npm install @superpenguin/js

Install only the provider packages you use (optional peers):

npm install openai @anthropic-ai/sdk @google/genai
npm install @deepgram/sdk @elevenlabs/elevenlabs-js
npm install ai  # Vercel AI SDK

Quick start

import OpenAI from "openai";
import { init, wrap } from "@superpenguin/js";

init({ apiKey: process.env.SP_API_KEY });

const openai = wrap(new OpenAI(), {
  metadata: {
    environment: "production",
    feature: "support_agent",
  },
});

await openai.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Write a concise reply." }],
  spMetadata: { customer_id: "cust_acme_123" },
});

wrap() auto-detects supported clients and strips spMetadata / sp_metadata before the request leaves your process.

Read current spend

Version 0.9.1 provides typed, low-latency spend reads. Use the same SDK key you use for ingestion; the authenticated organization is selected from that key.

import { init } from "@superpenguin/js";

const superpenguin = init({ apiKey: process.env.SP_API_KEY });

const current = await superpenguin.spend.get({ window: "1d" });

console.log(current.spendUsd);
console.log(current.asOf, current.stalenessMs);

1d means the current UTC calendar day, not the trailing 24 hours. Numbered windows include today plus the preceding N - 1 UTC days. month means the current UTC calendar month through today. Supported values are 1d through 7d, 14d, and month.

Filter by the feature or model recorded on usage events, or combine them:

const filtered = await superpenguin.spend.get({
  window: "7d",
  feature: "document-processing",
  model: "gpt-5",
});

The response contains:

FieldMeaning
spendMicrosExact USD-micro total as an integer string. Use this for calculations.
spendUsdConvenience floating-point USD value derived from spendMicros.
currency"USD".
windowResolved type, UTC start, exclusive UTC end, and timeZone.
asOfWhen the reader loaded the newest daily snapshot used by the response.
stalenessMsConservative estimate of how far the snapshot may trail usage already accepted by SuperPenguin.

There is no public freshThrough field; use asOf and stalenessMs to assess freshness. A spend result is advisory, not a reservation or concurrency-safe budget guarantee.

The SDK flushes locally buffered usage before the read by default. The ingest and materialization path is still asynchronous, so a flush does not guarantee a zero-staleness result. Set flush: false to skip that local flush. Identical concurrent reads in one process share a single flush and HTTP request.

Spend reads use https://spend.superpenguin.ai automatically. You do not need to set SP_SPEND_BASE_URL. Advanced staging or private-gateway setups can set that variable or pass spendBaseUrl; the override affects only spend reads, while ingestion continues to use SP_BASE_URL / baseUrl.

Invalid requests and service failures throw SuperPenguinSpendError, with code, retryable, and optional HTTP status properties. The SDK makes one bounded spend request and does not retry it automatically; retry only when retryable is true and doing so fits your application's policy. Codes are invalid_request, invalid_api_key, rate_limited, spend_unavailable, and request_failed.

Runtime behavior

  • Tracking never delays your model call: a wrapped call returns, and a wrapped stream ends, as soon as the provider is done. Events are sent in the background (since 0.17.3).
  • On Vercel and Next.js on Vercel, pending sends are registered with the request's waitUntil automatically. Elsewhere, pass init({ waitUntil }) (for example a Cloudflare Worker's ctx.waitUntil), or await flush() before a script, Lambda handler or serverless function returns. Node also flushes on beforeExit.
  • Transient ingest failures retry with backoff and requeue.
  • Attribution failures never fail your model call. With throwOnError: true, send errors are raised from flush().
  • For long-lived workers, use flushMode: "interval" and call flush() before shutdown.
  • With content capture on, serverless handlers must await flushContentCapture() before returning: samples are processed and uploaded in the background.

Content capture: upgrading to 0.16.0

Content capture is opt-in per organization (Settings, Pro or Enterprise) and sampled. A sample holds the whole model call: the request as sent (every message in order with its role, system prompt, tool definitions, tool calls and results, parameters) and the full response, never truncated. Secrets and personal data are redacted before anything leaves your process; binary data is replaced by its size. On your call's path the SDK only decides whether to sample and copies the top-level request; redaction, fingerprinting, serialization and compression run in the background. Usage events are sent first and are identical with capture on or off. See content capture for what is stored and redacted.

0.16.0 stores the whole sampled call (content schema 3). Earlier versions kept only the system text and the last user message and cut every field at 64 KB. To upgrade:

  1. npm install @superpenguin/js@latest. No other change is needed for calls that already go through wrap(), the Vercel AI SDK middleware or helpers, createLangChainCallback, trackPiStreamFn, submitSpan or trackBatchResult: they now send the full request and response.
  2. Set session_id (one conversation or agent run) and turn_id (one turn, reused across the model calls of a tool round-trip) from whichever source your integration uses (examples below). Samples without them cannot be grouped into conversations.
  3. In serverless handlers (Vercel, Lambda, Cloudflare Workers), call await flushContentCapture() before returning. Capture runs in the background after your call returns; a frozen or terminated function drops what has not been sent.
  4. Use exactly one reporting path per model call. Do not both wrap a client (or model) and report the same call with trackUsage: that counts its usage twice.

Each stored document also carries a blocks index (a SHA-256 fingerprint per system prompt, tool list, message and output item, computed after redaction) so repeated conversation prefixes can be deduplicated later. You do not need to do anything with it.

Content protocol 4 (0.17.0): deduplicated capture. When SuperPenguin turns on content protocol 4 for your organization, 0.17.0 uploads and stores each large piece of text in a call (any JSON string of 1 KiB or more, such as a file the agent read, a tool output or the system prompt) once per conversation per UTC day, instead of with every call. A stored call still rebuilds to exactly the document 0.16.0 would send. No code change is needed. Until protocol 4 is on, 0.17.0 captures exactly as 0.16.0 does.

  • Sampling. A whole conversation is sampled or not for the day, from its conversation key: session_id, or a field SuperPenguin sets for your organization. Every process makes the same choice.
  • Session ids. Use one stable session_id per agent run, shared by its subagents, and never a user id. A call without a conversation key is still captured, but gets no dedupe.
  • Process affinity. Dedupe works per process: a process uploads a conversation's texts the first time it sees them that day. Routing a run's calls to one process uploads the least.
  • The usage stamp. A captured call's usage event gains one field, content_sample_id, which links it to its content. No cost or usage value changes.
  • Options. forceSample and sampleRateMultiplier do not apply under protocol 4. allow: false still stops all capture. Counters for protocol 4 are in getContentCaptureStats().v4.

wrap() (OpenAI, Anthropic, Google GenAI, Bedrock and compatible clients). Defaults on the wrapper, per call with spMetadata, or for a whole run with withMetadata:

import OpenAI from "openai";
import { flushContentCapture, init, withMetadata, wrap } from "@superpenguin/js";

init({ apiKey: process.env.SP_API_KEY });
const openai = wrap(new OpenAI(), { metadata: { feature: "support_agent" } });

await withMetadata({ session_id: conversationId, customer_id: "cust_acme_123" }, async () => {
  await openai.chat.completions.create({
    model: "gpt-4o",
    messages,
    tools,
    spMetadata: { turn_id: turnId },
  });
});
await flushContentCapture(); // serverless only, before returning

Vercel AI SDK middleware (AI SDK 6 "v3", AI SDK 7 "v4"). The middleware cannot see generateText options, so put the ids in withMetadata (or in the middleware's metadata defaults):

import { generateText, wrapLanguageModel } from "ai";
import { openai } from "@ai-sdk/openai";
import { superpenguinMiddleware, withMetadata } from "@superpenguin/js";

const model = wrapLanguageModel({
  model: openai("gpt-4o"),
  middleware: superpenguinMiddleware({ specificationVersion: "v3", metadata: { feature: "chat" } }),
});

await withMetadata({ session_id: chatId, turn_id: messageId }, () =>
  generateText({ model, messages, tools }),
);

With trackGenerateText / trackStreamText, pass the ids in the call's metadata option; ids in the call's telemetry.metadata or experimental_telemetry.metadata are also used for samples. With submitSpan, span attributes sp.session_id / sp.turn_id or ai.telemetry.metadata.session_id / .turn_id are used.

LangChain / LangGraph and Pi (agent guide). Pass the ids in the invocation's metadata (LangChain) or establish them around the run (both):

await graph.invoke(input, {
  callbacks: [createLangChainCallback({ metadata: { feature: "research" } })],
  metadata: { session_id: threadId, turn_id: stepId },
});

await withMetadata({ session_id: sessionId }, () => agent.prompt(text)); // Pi with trackPiStreamFn

Batch helpers. trackBatchResult({ request, response, usageEvent }) samples batch and flex lines; pass metadata: { session_id, turn_id } (or set them on the usage event) to group them. See batch content capture.

Custom agent harnesses (trackUsage). If your harness calls the provider itself (raw fetch, a vendored client) and reports usage by hand, pass the exact request body you sent and the full response body you received. Usage is submitted first and is identical with or without them; the bodies then go through the same sampled, redacted, untruncated capture as wrap(), and are never read for unsampled calls:

import { flushContentCapture, trackUsage } from "@superpenguin/js";

const body = { model: "gpt-4.1", messages, tools, temperature: 0 };
const res = await fetch("https://api.openai.com/v1/chat/completions", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify(body),
});
const json = await res.json();

await trackUsage(
  {
    provider: "openai",
    model: json.model,
    usage: { inputTokens: json.usage.prompt_tokens, outputTokens: json.usage.completion_tokens },
    statusCode: res.status,
    request: body,      // the provider request body, in the provider's JSON shape
    response: json,     // the full provider response body
  },
  { metadata: { session_id: runId, turn_id: stepId, prompt_key: "coder" } },
);
await flushContentCapture(); // serverless only, before returning

For a streamed call, pass the response you assembled from the stream (all text, tool calls and usage). request alone or response alone is accepted; only the given half is stored.

Next

Agent runs and dynamic metadata

Version 0.11.0 and later supports execution-local metadata and agent framework adapters. See agent SDKs and dynamic metadata for Vercel AI SDK, OpenAI Agents, LangGraph/LangChain, Pi, OpenCode and custom harness examples. These APIs are not in 0.9.1 or 0.10.0.