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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@vishnu-vashishth/llm-sdk

v1.2.0

Published

A standalone, type-safe LLM SDK with multi-provider support, retry logic, context management, and intelligent tokenization.

Readme

LLM SDK

A flexible LLM SDK with streaming, context management, multi-provider support, and choice between integrated or custom flows.

Installation

npm install @vishnu-vashishth/llm-sdk zod

Two Approaches

1. Integrated Flow (ChatEngine)

Full-featured engine that handles everything:

import {
  ChatEngine,
  ModelRegistry,
  ProviderRegistry,
  ContextManager,
  TokenizerService,
  ProviderType,
} from '@vishnu-vashishth/llm-sdk';

// Setup
const models = new ModelRegistry();
models.registerModel({
  modelName: 'gpt-4',
  providerType: ProviderType.OPENAI,
  contextWindow: 8192,
  providerConfig: { apiKey: process.env.OPENAI_API_KEY },
  defaultSettings: { temperature: 0.7 },
});

const engine = new ChatEngine({
  models,
  providers: new ProviderRegistry(),
  context: new ContextManager(TokenizerService.getInstance()),
  messages: yourMessageStore,  // Implement MessageStore interface
  defaultModel: 'gpt-4',
});

// Use
const response = await engine.chat({
  conversationId: 'user-123',
  content: 'Hello!',
});

// Stream
for await (const delta of engine.stream({ conversationId: 'user-123', content: 'Hi' })) {
  process.stdout.write(delta.delta.content ?? '');
}

2. Custom Flow (Individual Components)

Build your own pipeline:

import {
  OpenAIProvider,
  ContextManager,
  TokenizerService,
  ModelRegistry,
  TruncationStrategy,
} from '@vishnu-vashishth/llm-sdk';

// 1. Get messages from your database
const messages = await db.getMessages(userId);

// 2. Truncate to fit context window
const ctx = new ContextManager(TokenizerService.getInstance());
const { messages: truncated } = await ctx.truncateMessagesWithMetadata(messages, {
  maxTokens: 8192,
  bufferTokens: 100,
  completionTokens: 1000,
  truncationStrategy: TruncationStrategy.SLIDING_WINDOW,
});

// 3. Send to provider
const provider = new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY });
const response = await provider.generateChat({
  model: 'gpt-4',
  messages: truncated,
  temperature: 0.7,
});

// 4. Stream tokens
for await (const delta of provider.generateChatStream({ model: 'gpt-4', messages })) {
  process.stdout.write(delta.delta.content ?? '');
}

Core Components

| Component | Purpose | |-----------|---------| | ChatEngine | Integrated flow coordinator | | ModelRegistry | Model configurations | | ProviderRegistry | Provider instances | | ContextManager | Token counting, truncation, caching | | OpenAIProvider | OpenAI-compatible API calls | | PromptService | Template rendering with Zod validation |

Streaming

// Async generator
for await (const delta of provider.generateChatStream(payload)) {
  process.stdout.write(delta.delta.content ?? '');
}

// Callbacks
await provider.generateChatStreamWithCallbacks(payload, {
  onToken: (token) => process.stdout.write(token),
  onComplete: (response) => console.log('Done'),
});

Context Management

const ctx = new ContextManager(tokenizer, { cacheSize: 5000 });

// Token counts are cached
const tokens = await ctx.countMessagesTokens(messages);

// Incremental session management
ctx.createSession('chat-1', { maxTokens: 8192 });
await ctx.appendToSession('chat-1', newMessages);

// Cache stats
console.log(ctx.getCacheStats()); // { hits, misses, hitRate }

Error Handling

import { RateLimitError, TimeoutError, isRecoverableError } from '@vishnu-vashishth/llm-sdk';

try {
  await provider.generateChat(payload);
} catch (error) {
  if (error instanceof RateLimitError) {
    await delay(error.retryAfter);
  } else if (isRecoverableError(error)) {
    // Retry
  }
}

Implementing Stores

// MessageStore interface
interface MessageStore {
  getMessages(conversationId: string, limit?: number): Promise<Message[]>;
  saveMessage(conversationId: string, message: Message): Promise<void>;
}

// MemoryStore interface (optional)
interface MemoryStore {
  getRelevant(query: string, limit?: number): Promise<Memory[]>;
}

Documentation

License

ISC