npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@csaimonitor/sdk

v0.1.0

Published

Production-ready Node.js/TypeScript SDK for Customer Support AI Monitor

Downloads

92

Readme

@csaimonitor/sdk

npm version Node.js Support License: MIT

Production-ready Node.js/TypeScript SDK for Customer Support AI Monitor. Track events, measure performance, analyze costs, and gain insights into your AI systems.

Features

  • Zero Boilerplate: One decorator and it works
  • Automatic Tracking: Input, output, timing, and errors captured automatically
  • Batching: 10x reduction in API calls with smart batching (default: 10 events per batch)
  • Background Flushing: Automatic flush every 5 seconds
  • Async Support: Full async/await compatibility with AsyncCSMonitor
  • Reliable: Never crashes your application - all errors are caught and handled
  • Type Safe: Complete TypeScript definitions for excellent IDE support
  • Flexible: Decorator, context manager, or manual tracking patterns

Quick Start (< 5 minutes)

Installation

npm install @csaimonitor/sdk

Basic Usage

import { CSMonitor } from '@csaimonitor/sdk';

// Initialize monitor
const monitor = new CSMonitor({
  apiKey: 'your_api_key_here_minimum_32_characters_long',
  agentId: 'my_agent',
  apiUrl: 'http://localhost:3002/api/v1'
});

// Track any function with a decorator
@monitor.track()
function chatWithUser(message: string): string {
  return `AI response to: ${message}`;
}

// Call your function normally
const result = chatWithUser('Hello!');

// Flush events before exit
monitor.flush();
monitor.close();

That's it! Events are now flowing to your dashboard.

Usage Patterns

1. Decorator Pattern (Recommended)

The simplest way to track functions:

@monitor.track()
function myAgentFunction(inputData: string): string {
  // Your AI logic here
  return process(inputData);
}

With custom event type and metadata:

@monitor.track({
  eventType: 'query',
  metadata: { model: 'gpt-4', version: '1.0' }
})
function askQuestion(question: string): string {
  return generateAnswer(question);
}

2. Context Manager Pattern

For fine-grained control:

const event = monitor.trackEvent('llm_call', { prompt: 'Hello' });

try {
  const result = callLLM('Hello');
  
  // Set output and metadata
  event.setOutput({ response: result });
  event.setCost(0.0042);  // Track cost in USD
  event.setMetadata({ model: 'gpt-4', tokens: 150 });
  event.finish();
} catch (error) {
  event.finish(error);
  throw error;
}

3. Manual Tracking

For legacy code or maximum control:

monitor.logEvent({
  eventType: 'decision',
  inputData: { query: 'user input' },
  outputData: { answer: 'AI response' },
  metadata: { model: 'gpt-4' },
  costUsd: 0.01,
  latencyMs: 250,
  status: 'success'
});

4. Async/Await Support

For async functions, use AsyncCSMonitor:

import { AsyncCSMonitor } from '@csaimonitor/sdk';

const monitor = new AsyncCSMonitor({
  apiKey: 'your_key',
  agentId: 'async_agent',
  apiUrl: 'http://localhost:3002/api/v1'
});

await monitor.start();

@monitor.track()
async function asyncFunction(data: string): Promise<string> {
  await someAsyncOperation();
  return `Processed: ${data}`;
}

const result = await asyncFunction('test');
await monitor.flush();
await monitor.stop();

Configuration Options

| Option | Type | Required | Default | Description | |--------|------|----------|---------|-------------| | apiKey | string | Yes | - | API key for authentication (min 32 chars) | | agentId | string | Yes | - | Identifier for the agent being monitored | | apiUrl | string | No | Production URL | Base URL for the API | | batchSize | number | No | 10 | Number of events to batch before sending (1-100) | | flushInterval | number | No | 5.0 | Seconds between automatic flushes | | retryAttempts | number | No | 3 | Maximum retry attempts for failed requests (0-10) | | timeout | number | No | 30 | Request timeout in seconds | | debug | boolean | No | false | Enable debug logging | | enabled | boolean | No | true | Enable/disable tracking | | redactKeys | string[] | No | [] | Array of keys to redact from event data | | onError | function | No | - | Callback function for error handling |

Example Configuration

const monitor = new CSMonitor({
  apiKey: 'your_key_here',
  agentId: 'my_agent',
  apiUrl: 'http://localhost:3002/api/v1',
  batchSize: 20,
  flushInterval: 10.0,
  retryAttempts: 5,
  timeout: 60,
  debug: true,
  redactKeys: ['password', 'api_key', 'token'],
  onError: (error) => {
    console.error('CSMonitor error:', error);
    // Log to your error tracking service
  }
});

Error Handling

The SDK is designed to never crash your application. All errors are caught and handled gracefully:

const monitor = new CSMonitor({
  apiKey: 'your_key',
  agentId: 'my_agent',
  onError: (error) => {
    // Handle errors (log to Sentry, etc.)
    console.error('Monitoring error:', error);
  }
});

// Even if the API is down, your app continues to work
@monitor.track()
function myFunction() {
  return 'result';
}

Data Redaction

Automatically redact sensitive data:

const monitor = new CSMonitor({
  apiKey: 'your_key',
  agentId: 'my_agent',
  redactKeys: ['password', 'api_key', 'token', 'secret']
});

@monitor.track()
function login(username: string, password: string) {
  // password will be redacted as [REDACTED] in events
  return authenticate(username, password);
}

Performance

  • Minimal Overhead: < 1ms per tracked function call
  • Non-Blocking: All API calls happen in the background
  • Efficient Batching: 10x reduction in API calls
  • Automatic Flushing: Events are sent automatically every 5 seconds

API Reference

CSMonitor

Main synchronous client for tracking events.

Methods

  • track(options?): Decorator for tracking functions
  • trackEvent(eventType, inputData?): Create a context manager for tracking
  • logEvent(options): Manually log an event
  • flush(): Flush all pending events immediately (blocking)
  • close(): Close the monitor and cleanup resources

AsyncCSMonitor

Asynchronous client for tracking events with full async/await support.

Methods

  • start(): Start the background flushing task
  • stop(): Stop the background task and flush remaining events
  • track(options?): Decorator for tracking async functions
  • trackEvent(eventType, inputData?): Create an async context manager
  • logEvent(options): Manually log an event (async)
  • flush(): Flush all pending events immediately (async)

Examples

See the examples/ directory for complete examples:

  • basic-usage.ts - Simple decorator pattern
  • async-usage.ts - Async/await examples
  • context-manager.ts - Context manager pattern
  • manual-tracking.ts - Direct event logging
  • error-handling.ts - Error handling and redaction

TypeScript Support

Full TypeScript support with complete type definitions:

import { CSMonitor, Event, EventMetadata, CSMonitorConfig } from '@csaimonitor/sdk';

const monitor: CSMonitor = new CSMonitor({
  apiKey: 'your_key',
  agentId: 'my_agent'
});

Troubleshooting

Events not appearing in dashboard

  1. Check that apiUrl is correct
  2. Verify apiKey is valid (min 32 characters)
  3. Ensure agentId matches your agent
  4. Call monitor.flush() before application exit
  5. Enable debug: true to see detailed logs

High memory usage

  • Reduce batchSize if you have many events
  • Reduce flushInterval to flush more frequently
  • Call monitor.flush() periodically in long-running applications

Network errors

  • Increase timeout for slow networks
  • Increase retryAttempts for unreliable connections
  • Check onError callback for detailed error information

Requirements

  • Node.js 16.0.0 or higher
  • TypeScript 5.0.0 or higher (for TypeScript projects)

License

MIT License - see LICENSE file for details.

Support

For issues, questions, or contributions, please visit our GitHub repository.

Changelog

See CHANGELOG.md for version history.