Skip to Content
SDK ReferenceNeuraMeter Class

NeuraMeter Class

The low-level class for recording cost events, checking guards, and managing event batching. Most users should use withNeuraMeter() instead — this class is for advanced use cases and custom integrations.

Constructor

import { NeuraMeter } from '@neurameter/core'; const meter = new NeuraMeter({ apiKey: 'nm_xxx', projectId: 'proj_xxx', endpoint: 'https://meter.neuria.tech', // optional batchSize: 50, // optional flushIntervalMs: 5000, // optional guards: { /* ... */ }, // optional });

Config

interface NeuraMeterConfig { apiKey: string; projectId: string; endpoint?: string; // default: ingestion worker URL batchSize?: number; // default: 50 flushIntervalMs?: number; // default: 5000 guards?: GuardsConfig; // optional guardrails }

Methods

record(event)

Records a cost event. Events are buffered and sent in batches.

meter.record({ traceId: crypto.randomUUID(), spanId: crypto.randomUUID(), agentName: 'MyAgent', provider: 'openai', model: 'gpt-4o', inputTokens: 1500, outputTokens: 300, reasoningTokens: 0, cachedTokens: 0, costMicrodollars: 6750, // $0.00675 latencyMs: 1200, });

startTrace(opts)

Creates a new Trace instance for grouping related events.

const trace = meter.startTrace({ agentName: 'MyAgent', customerId: 'cust_123', taskName: 'summarize-document', });

checkGuards(params)

Checks guard rules before an API call. Only works if guards was configured.

const result = meter.checkGuards({ messages: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'Hello' }, ], model: 'gpt-4o', provider: 'openai', agentName: 'MyAgent', }); if (result?.decision === 'block') { // handle blocked request }

Returns GuardCheckResult | null (null if no guards configured).

runAutoOptimize(params)

Runs the auto-optimize flow when guards are in auto-optimize mode.

const optimizeResult = await meter.runAutoOptimize({ guardResult: result, messages: messages, model: 'gpt-4o', agentName: 'MyAgent', }); if (optimizeResult?.action === 'retry') { // retry with optimizeResult.messages }

getHourlyCostDollars(agentName)

Returns the rolling 1-hour cost for an agent in dollars.

const hourlyCost = meter.getHourlyCostDollars('MyAgent'); // e.g. 2.45 (dollars)

flush()

Manually flushes all buffered events to the ingestion API.

await meter.flush();

destroy()

Stops the auto-flush timer and flushes remaining events. Call this on application shutdown.

await meter.destroy();

Event Batching

Events are automatically batched and sent when:

  • The buffer reaches batchSize (default: 50 events)
  • The flush timer fires (default: every 5 seconds)

Failed sends are retried on the next flush cycle. The timer is unref()’d so it won’t prevent Node.js from exiting.