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

@revenium/anthropic

v1.0.8

Published

Transparent TypeScript middleware for automatic Revenium usage tracking with Anthropic Claude AI

Readme

Revenium Middleware for Anthropic (Node.js)

npm version Node Versions Documentation Website License: MIT

Automatically track and meter your Anthropic Claude API usage with Revenium. This middleware provides seamless integration with Anthropic Claude SDK, requiring minimal code changes and featuring native TypeScript support.

Features

  • Seamless Integration: Drop-in replacement with zero code changes required
  • Complete Metering: Track tokens, costs, and performance metrics automatically
  • Custom Metadata: Add business context with native TypeScript support
  • Streaming Support: Real-time streaming with comprehensive analytics
  • Tool Use Support: Full support for Anthropic's function calling and tools
  • Multi-modal Support: Works with text, images, and all Claude capabilities
  • Type Safe: Complete TypeScript support with no type casting required
  • Fire-and-forget: Never blocks your application flow
  • Analytics: Detailed usage analytics and reporting

Getting Started

1. Create Project Directory

# Create and navigate to project directory
mkdir my-anthropic-project
cd my-anthropic-project

# Initialize npm project
npm init -y

# Install dependencies
npm install @revenium/anthropic @anthropic-ai/sdk dotenv tsx
npm install --save-dev typescript @types/node

2. Configure Environment Variables

Create a .env file:

REVENIUM_METERING_API_KEY="hak_your_revenium_key"
ANTHROPIC_API_KEY="sk-ant-your_anthropic_key"

Note: REVENIUM_METERING_BASE_URL defaults to https://api.revenium.ai and doesn't need to be set unless using a different environment.

3. Run Your First Example

Run the getting started example:

npx tsx node_modules/@revenium/anthropic/examples/getting_started.ts

Or with debug logging:

# Linux/macOS
REVENIUM_DEBUG=true npx tsx node_modules/@revenium/anthropic/examples/getting_started.ts

# Windows (PowerShell)
$env:REVENIUM_DEBUG="true"; npx tsx node_modules/@revenium/anthropic/examples/getting_started.ts

For more examples and TypeScript patterns, see examples/README.md.

Requirements

  • Node.js 18+
  • TypeScript 5.0+ (for TypeScript projects)
  • Anthropic SDK (@anthropic-ai/sdk) v0.20.0+
  • Revenium API key

What Gets Tracked

The middleware automatically captures:

  • Token Usage: Input and output tokens for accurate billing
  • Request Duration: Total time for each API call
  • Model Information: Which Claude model was used
  • Operation Type: Chat completion, streaming, tool use, etc.
  • Error Tracking: Failed requests and error details
  • Streaming Metrics: Time to first token for streaming responses
  • Custom Metadata: Business context you provide

Advanced Usage

Initialization Options

The middleware supports three initialization patterns:

Automatic (Recommended) - Simply import the middleware and it auto-initializes:

import "@revenium/anthropic";
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();
// Tracking works automatically if env vars are set

Explicit - Call initialize() for error handling control

Manual - Use configure() to set all options programmatically

For detailed examples of all initialization patterns, see examples/.

Streaming Responses

Streaming is fully supported with real-time token tracking and time-to-first-token metrics. The middleware automatically tracks streaming responses without any additional configuration.

See examples/advanced-features.ts for working streaming examples.

Custom Metadata Tracking

Add business context to track usage by organization, user, task type, or custom fields. Pass a usageMetadata object with any of these optional fields:

| Field | Description | Use Case | |-------|-------------|----------| | traceId | Unique identifier for session or conversation tracking | Link multiple API calls together for debugging, user session analytics, or distributed tracing across services | | taskType | Type of AI task being performed | Categorize usage by workload (e.g., "chat", "code-generation", "doc-summary") for cost analysis and optimization | | subscriber.id | Unique user identifier | Track individual user consumption for billing, rate limiting, or user analytics | | subscriber.email | User email address | Identify users for support, compliance, or usage reports | | subscriber.credential.name | Authentication credential name | Track which API key or service account made the request | | subscriber.credential.value | Authentication credential value | Associate usage with specific credentials for security auditing | | organizationId | Organization or company identifier | Multi-tenant cost allocation, usage quotas per organization | | subscriptionId | Subscription plan identifier | Track usage against subscription limits, identify plan upgrade opportunities | | productId | Your product or feature identifier | Attribute AI costs to specific features in your application (e.g., "chatbot", "email-assistant") | | agent | AI agent or bot identifier | Distinguish between multiple AI agents or automation workflows in your system | | responseQualityScore | Custom quality rating (0.0-1.0) | Track user satisfaction or automated quality metrics for model performance analysis |

All metadata fields are optional. Custom fields beyond the standard ones are automatically preserved and sent to Revenium.

Resources:

Metadata Fields

The middleware automatically sends the following fields to Revenium's /meter/v2/ai/completions endpoint:

| Field | Type | Source | Description | |-------|------|--------|-------------| | stopReason | string | Anthropic Response | Why completion stopped: "END", "MAX_TOKENS", "STOP_SEQUENCE", "TOOL_USE" | | costType | string | Fixed | Always "AI" for AI completions | | isStreamed | boolean | Request Type | Whether response was streamed | | taskType | string | usageMetadata | Optional task categorization | | agent | string | usageMetadata | Optional agent identifier | | operationType | string | Fixed | Always "CHAT" for message completions | | inputTokenCount | number | Anthropic Usage | Input tokens consumed | | outputTokenCount | number | Anthropic Usage | Output tokens generated | | reasoningTokenCount | number | Fixed | Always 0 (Anthropic doesn't report reasoning tokens) | | cacheCreationTokenCount | number | Anthropic Usage | Tokens used for prompt caching creation | | cacheReadTokenCount | number | Anthropic Usage | Tokens read from prompt cache | | totalTokenCount | number | Calculated | Sum of input + output tokens | | organizationId | string | usageMetadata | Optional organization identifier | | productId | string | usageMetadata | Optional product identifier | | subscriber | object | usageMetadata | Optional subscriber info (id, email, credential) | | subscriptionId | string | usageMetadata | Optional subscription plan identifier | | model | string | Request | Anthropic model used (e.g., "claude-3-5-haiku-20241022") | | transactionId | string | Generated | Unique request identifier (UUID) | | responseTime | string | Timestamp | ISO 8601 timestamp of response completion | | requestDuration | number | Measured | Total request duration in milliseconds | | provider | string | Fixed | Always "Anthropic" | | requestTime | string | Timestamp | ISO 8601 timestamp when request started | | completionStartTime | string | Timestamp | ISO 8601 timestamp when completion generation started | | timeToFirstToken | number | Measured | Milliseconds from request start to first token (streaming only) | | traceId | string | usageMetadata | Optional trace identifier for request correlation | | responseQualityScore | number | usageMetadata | Optional quality rating (0.0-1.0) | | middlewareSource | string | Fixed | Always "nodejs" to identify this middleware | | Custom Fields | any | usageMetadata | Any additional fields in usageMetadata are preserved |

Note: Fields marked as "usageMetadata" come from the optional usageMetadata object you pass to messages.create().

Resources:

Configuration Options

Environment Variables

| Variable | Required | Default | Description | | ---------------------------- | -------- | -------------------------- | --------------------------------- | | REVENIUM_METERING_API_KEY | Yes | - | Your Revenium API key | | ANTHROPIC_API_KEY | Yes | - | Anthropic Claude API key | | REVENIUM_METERING_BASE_URL | No | https://api.revenium.ai | Revenium metering API base URL | | REVENIUM_DEBUG | No | false | Enable debug logging (true/false) |

Manual Configuration

For programmatic configuration instead of environment variables, use the configure() function. See the initialization options above and examples/ for details.

Troubleshooting

Common Issues

"Missing API Key" Error

# Make sure you've set the API key
export ANTHROPIC_API_KEY="sk-ant-your-actual-api-key"

# Verify it's set
echo $ANTHROPIC_API_KEY

"Requests not being tracked"

# Verify Revenium configuration
export REVENIUM_METERING_API_KEY="hak-your-actual-revenium-key"

# Enable debug logging to see what's happening
export REVENIUM_DEBUG="true"

TypeScript errors with usageMetadata

  • Ensure you're importing the middleware before using Anthropic
  • Check that your TypeScript version is 4.5+ for module augmentation
  • Verify you're using the latest version: npm update @revenium/anthropic

Build/Import Errors

# Clean and reinstall
rm -rf node_modules package-lock.json
npm install

# For TypeScript projects
npm run build

Debug Mode

Enable detailed logging to troubleshoot issues:

export REVENIUM_DEBUG="true"
node your-script.js

This will show:

  • Request/response details
  • Token counting information
  • Metering data being sent
  • Error details

Look for log messages like:

  • [Revenium] Anthropic request intercepted
  • [Revenium] Usage metadata extracted
  • [Revenium] Revenium tracking successful

Included Examples

The package includes these example files:

  • basic-usage.ts: Simple chat completions with all initialization methods
  • advanced-features.ts: Streaming, tools, and custom metadata

All examples are in the examples/ directory of the installed package. For detailed TypeScript patterns and usage, see examples/README.md.

How It Works

  1. Automatic Patching: When imported, the middleware patches Anthropic's messages.create method
  2. Request Interception: All Anthropic requests are intercepted to extract metadata
  3. Usage Extraction: Token counts, model info, and timing data are captured
  4. Async Tracking: Usage data is sent to Revenium in the background (fire-and-forget)
  5. Transparent Response: Original Anthropic responses are returned unchanged

The middleware never blocks your application - if Revenium tracking fails, your Anthropic requests continue normally.

Documentation

For detailed documentation, visit docs.revenium.io.
For contributor lifecycle, validation, and provider metadata, see docs/standardization/README.md.

Contributing

See CONTRIBUTING.md

Code of Conduct

See CODE_OF_CONDUCT.md

Security

See SECURITY.md

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For issues, feature requests, or contributions:

Development

For development and testing instructions, see DEVELOPMENT.md.


Built by Revenium