Back to Guides

Node.js SDK

Alpha

Complete API reference for the Bear Lumen Node.js SDK. Track AI usage, manage end users, and analyze costs with full TypeScript support.

Also available: Python SDK — same API surface with Pythonic conventions.

Installation & Configuration

Install the SDK from npm:

npm install @bearlumen/node-sdk

Initialize the client with your API key:

import { BearLumen } from '@bearlumen/node-sdk';

const bearLumen = new BearLumen({
  apiKey: 'bl_live_...',                           // Required
  baseUrl: 'https://api.bearlumen.com',            // Optional (default)
  timeout: 30000,                                  // Optional: 30s default
});
OptionTypeDefaultDescription
apiKeystringRequired. Your API key.
baseUrlstringapi.bearlumen.comOptional. API base URL.
timeoutnumber30000Optional. Request timeout in milliseconds.

End Users

Manage end users whose AI usage you track.

MethodDescription
endUsers.create(data)Create a new end user
endUsers.update(id, data)Update an end user
endUsers.list(params?)List end users with optional filtering
endUsers.deactivate(id)Soft-delete an end user
endUsers.reactivate(id)Restore a deactivated end user

Create an End User

const { endUser } = await bearLumen.endUsers.create({
  externalId: 'user_123',       // Required: your unique identifier
  name: 'AI Startup Inc',       // Optional
  email: '[email protected]', // Optional: for portal access
  metadata: { plan: 'pro' },    // Optional: max 10KB
});

Update an End User

const { endUser } = await bearLumen.endUsers.update('eu_12345', {
  name: 'Updated Name',
  metadata: { plan: 'enterprise' },
});

List End Users

const { endUsers, total, activeCount, deactivatedCount } =
  await bearLumen.endUsers.list({
    status: 'ACTIVE',  // Optional: 'ACTIVE' or 'DEACTIVATED'
    limit: 50,         // Optional: default 100, max 1000
    offset: 0,         // Optional
  });

Deactivate / Reactivate

// Soft delete (usage history retained)
await bearLumen.endUsers.deactivate('eu_12345');

// Restore access
await bearLumen.endUsers.reactivate('eu_12345');

Subscriptions

Link end users to pricing plans.

MethodDescription
subscriptions.create(data)Create a new subscription
subscriptions.retrieve(id)Get a subscription by ID
subscriptions.update(id, data)Update a subscription
subscriptions.cancel(id)Cancel a subscription
subscriptions.list(params?)List all subscriptions

Create a Subscription

const subscription = await bearLumen.subscriptions.create({
  userId: 'eu_12345',                              // Required
  pricingPlanId: 'plan_pro_monthly',                // Required
  currentPeriodStart: new Date().toISOString(),      // Required (ISO 8601)
  currentPeriodEnd: new Date(Date.now() + 30 * 86400000).toISOString(), // Required
  stripeSubscriptionId: 'sub_stripe_abc',           // Optional
  metadata: { source: 'self-serve' },               // Optional
});

Retrieve, Update, Cancel, List

// Get by ID
const sub = await bearLumen.subscriptions.retrieve('sub_12345');

// Update fields
const updated = await bearLumen.subscriptions.update('sub_12345', {
  pricingPlanId: 'plan_enterprise',
});

// Cancel
const cancelled = await bearLumen.subscriptions.cancel('sub_12345');

// List with optional filters
const { data, total } = await bearLumen.subscriptions.list({
  userId: 'eu_12345', // Optional
  limit: 20,          // Optional
  offset: 0,          // Optional
});

Usage Tracking

Record and query AI usage events for billing and cost analysis.

MethodDescription
usage.record(data)Record a usage event
usage.recordBatch(events)Record multiple events (max 1000)
usage.query(params?)Query usage events
usage.aggregation(params?)Get aggregated usage by metric
usage.summary(params?)Get high-level usage summary

Record a Single Event

const result = await bearLumen.usage.record({
  eventType: 'token_usage',        // Required
  metricName: 'llm_tokens_input',  // Required
  quantity: 1500,                   // Required
  subscriptionId: 'sub_123',       // Optional
  idempotencyKey: 'unique-key',    // Recommended: prevents duplicates
  metadata: {                      // Optional
    model: 'claude-3-haiku',
    provider: 'anthropic',
  },
});

console.log(result.eventId);   // Unique event ID
console.log(result.recorded);  // true if new, false if duplicate

Agent and Workflow Attribution

Pass agent_id and workflow_id as convenience parameters. They are automatically folded into the event metadata, enabling cost attribution queries.

await bearLumen.usage.record({
  eventType: 'token_usage',
  metricName: 'llm_tokens',
  quantity: 50000,
  agent_id: 'support-agent',       // Convenience: folded into metadata
  workflow_id: 'onboarding-flow',  // Convenience: folded into metadata
  idempotencyKey: `agent-${Date.now()}`,
});

Record Batch Events

const result = await bearLumen.usage.recordBatch([
  {
    eventType: 'token_usage',
    metricName: 'llm_tokens',
    quantity: 1000,
    idempotencyKey: 'batch-1-evt-1',
  },
  {
    eventType: 'token_usage',
    metricName: 'llm_tokens',
    quantity: 2000,
    idempotencyKey: 'batch-1-evt-2',
  },
]);

console.log(`Recorded: ${result.recordedCount}, Skipped: ${result.skippedCount}`);

Query Usage Events

const events = await bearLumen.usage.query({
  subscriptionId: 'sub_123',
  metricName: 'llm_tokens_input',
  startDate: '2024-01-01',
  endDate: '2024-01-31',
  limit: 100,
});

Get Aggregated Usage

const aggregation = await bearLumen.usage.aggregation({
  subscriptionId: 'sub_123',
  startDate: '2024-01-01',
  endDate: '2024-01-31',
});

Get Usage Summary

const summary = await bearLumen.usage.summary({
  subscriptionId: 'sub_123',
  startDate: '2024-01-01',
  endDate: '2024-01-31',
});

Cost Attribution

Analyze AI costs by agent and workflow. Requires usage events recorded with agent_id or workflow_id metadata.

MethodDescription
costAttribution.byAgent(params)Cost breakdown grouped by agent
costAttribution.byWorkflow(params)Cost breakdown grouped by workflow
costAttribution.listAgents(params)List unique agent identifiers
costAttribution.listWorkflows(params)List unique workflow identifiers

Cost Breakdown by Agent

const breakdown = await bearLumen.costAttribution.byAgent({
  startDate: '2024-01-01T00:00:00Z',
  endDate: '2024-01-31T23:59:59Z',
});

for (const item of breakdown.items) {
  console.log(`${item.attributionValue}: $${item.totalCost} (${item.percentOfTotal}%)`);
  console.log(`  Tokens: ${item.inputTokens} in / ${item.outputTokens} out`);
  console.log(`  Events: ${item.eventCount}`);
}
console.log(`Total: $${breakdown.totalCost}`);

Cost Breakdown by Workflow

const breakdown = await bearLumen.costAttribution.byWorkflow({
  startDate: '2024-01-01T00:00:00Z',
  endDate: '2024-01-31T23:59:59Z',
});

List Unique Agents

const { values: agents } = await bearLumen.costAttribution.listAgents({
  startDate: '2024-01-01T00:00:00Z',
  endDate: '2024-01-31T23:59:59Z',
});

console.log('Active agents:', agents); // ['support-agent', 'sales-agent', ...]

List Unique Workflows

const { values: workflows } = await bearLumen.costAttribution.listWorkflows({
  startDate: '2024-01-01T00:00:00Z',
  endDate: '2024-01-31T23:59:59Z',
});

console.log('Active workflows:', workflows);

TypeScript Types

The SDK is written in TypeScript and includes full type definitions. Import any type you need:

import {
  BearLumen,
  BearLumenConfig,
  EndUser,
  EndUserCreateInput,
  EndUserUpdateInput,
  Subscription,
  SubscriptionCreateInput,
  UsageRecordInput,
  UsageRecordResponse,
  CostBreakdownResponse,
  CostBreakdownItem,
  AttributionValuesResponse,
  AttributionDateRange,
  BearLumenApiError,
} from '@bearlumen/node-sdk';

Available Types

BearLumenBearLumenConfigEndUserEndUserCreateInputEndUserUpdateInputSubscriptionSubscriptionCreateInputUsageRecordInputUsageRecordResponseCostBreakdownResponseCostBreakdownItemAttributionValuesResponseAttributionDateRangeBearLumenApiError

Requirements

  • Node.js >= 18.0.0