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

@dysporium-sdk/utils

v3.0.0

Published

Utility functions for Dysporium SDK - caching, cost tracking, middleware

Readme

@dysporium-sdk/utils

Utility functions for Dysporium SDK - caching, cost tracking, and middleware.

Installation

npm install @dysporium-sdk/utils

Features

  • Request/Response Hooks - Middleware for logging, metrics, and custom processing
  • Response Caching - In-memory and semantic caching for LLM responses
  • Cost Tracking - Track and estimate costs across OpenAI, Anthropic, and Qwen

Usage

Request/Response Hooks

import { MiddlewareManager, createLoggingHook } from '@dysporium-sdk/utils';

// Create middleware manager with logging
const middleware = new MiddlewareManager(createLoggingHook());

// Add custom hooks
middleware.beforeRequest((ctx) => {
  console.log(`Request ${ctx.requestId} to ${ctx.modelId}`);
});

middleware.afterResponse((ctx) => {
  console.log(`Response in ${ctx.duration}ms, used ${ctx.result.usage.totalTokens} tokens`);
});

middleware.onError((ctx) => {
  console.error(`Error: ${ctx.error.message}`);
});

Response Caching

import { MemoryCache, generateCacheKey } from '@dysporium-sdk/utils';

// Create cache with 1 hour TTL
const cache = new MemoryCache({ ttl: 3600000, maxSize: 1000 });

// Check cache before making request
const key = generateCacheKey(options, modelId, provider);
const cached = cache.get(key);

if (cached) {
  return cached;
}

// Make request and cache result
const result = await generateText(options);
cache.set(key, result);

// Get cache stats
console.log(cache.stats()); // { hits, misses, size, hitRate }

Semantic Cache

import { SemanticCache } from '@dysporium-sdk/utils';

// Cache responses based on semantic similarity
const cache = new SemanticCache({
  similarityThreshold: 0.95,
  ttl: 3600000,
});

// Find similar cached response
const embedding = await embed({ model, value: prompt });
const cached = cache.findSimilar(embedding);

if (!cached) {
  const result = await generateText(options);
  cache.add(prompt, embedding, result);
}

Cost Tracking

import { 
  CostTracker, 
  calculateCost, 
  formatCost,
  formatSummary 
} from '@dysporium-sdk/utils';

// Calculate cost for a single request
const cost = calculateCost(result.usage, 'gpt-4o', 'openai');
console.log(formatCost(cost.totalCost)); // $0.0123

// Track costs over time
const tracker = new CostTracker();

// Track each request
tracker.track(result.usage, 'gpt-4o', 'openai');
tracker.track(result2.usage, 'claude-sonnet-4-5', 'anthropic');

// Get summary
const summary = tracker.getSummary();
console.log(formatSummary(summary));

// Check budget
if (tracker.isBudgetExceeded(10.00)) {
  console.warn('Daily budget exceeded!');
}

// Get cost for last hour
const hourCost = tracker.getCostForPeriod(60);

Pricing Data

import { 
  OPENAI_PRICING, 
  ANTHROPIC_PRICING, 
  QWEN_PRICING 
} from '@dysporium-sdk/utils';

// Access pricing for any model
console.log(OPENAI_PRICING['gpt-4o']);
// { inputPer1M: 2.50, outputPer1M: 10.00, cachedInputPer1M: 1.25 }

console.log(ANTHROPIC_PRICING['claude-sonnet-4-5']);
// { inputPer1M: 3.00, outputPer1M: 15.00, cachedInputPer1M: 0.30 }

API Reference

Hooks

  • MiddlewareManager - Manage request/response hooks
  • createLoggingHook() - Built-in logging hook
  • createMetricsHook() - Built-in metrics collection hook

Caching

  • MemoryCache - In-memory LRU cache with TTL
  • SemanticCache - Similarity-based caching using embeddings
  • generateCacheKey() - Generate deterministic cache keys
  • createCacheMiddleware() - Create cache middleware

Cost Tracking

  • CostTracker - Track costs over time
  • calculateCost() - Calculate cost from usage
  • estimateCost() - Estimate cost from token counts
  • formatCost() - Format cost as string
  • formatSummary() - Format cost summary

License

MIT